0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PowerShell 5.1】バッチから実行する方法(実行ポリシー変更不要)

Last updated at Posted at 2024-07-07

はじめに

前提

下記環境での動作を前提としている。
PowerShell 5.1

本記事について

実行ポリシーを変更せずに、PowerShellスクリプトをバッチから実行する方法を示す。

実行する方法

結論から申し上げると、下記方法で、実行ポリシーを変更せずに、バッチからPowerShellスクリプトを実行できる。

  1. PowerShellスクリプト(.ps1)をワンラインにする。
  2. PowerShellの起動引数にワンラインにしたPowerShellスクリプトを指定する。
  3. 保存したバッチを実行する。
PowerShell実行.bat
PowerShell -c  "$msg = 'これはテストです。';Write-Host $msg; Get-ChildItem | %% {  Write-Host $_.FullName };"

PowerShellの引数する方法

「変換前.ps1」のスクリプトなら、「変換後.bat」に書き換える。

変換前.ps1
$msg = "これはテストです。"
Write-Host $msg
Get-ChildItem | % {  Write-Host $_.FullName }
変換後.bat
PowerShell -c  "$msg = 'これはテストです。';Write-Host $msg; Get-ChildItem | %% {  Write-Host $_.FullName };"

注意事項

「"」を含む場合

「"」(ダブルクォーテーション)は、「'」(シングルクォーテーション)にする。

「%」を含む場合

「%」は、2つにする。
バッチにした際、「%」が1つの場合は「%」が消えてしまう。
(「%」が消える理由は、調査中である。)

おわりに

下記方法でバッチからPowerShellスクリプトを実行する方法を紹介した。

  1. PowerShellスクリプトをワンラインにする。
  2. PowerShellの「-c」オプションに、ワンラインにしたPowerShellスクリプトを指定する。
  3. 保存したバッチを実行する。

※ 本記事は、実行ポリシーの回避を推奨するものではない。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?