LoginSignup
30
30

More than 5 years have passed since last update.

コマンドプロンプトから PowerShell を実行する

Last updated at Posted at 2015-05-14

Windows 向けにスクリプトを書く際に、コマンドプロンプトで出来る事は限られてくるので PowerShell を使いたい場合があります。

コマンドプロンプトから値を渡して PowerShell で実行できれば良いのに!という要望を叶えるための方法を紹介します。

コマンドプロンプトから PowerShell を呼び出す

powershell -Command "ls"

これで、 powershell で ls コマンドを実行します。

powershell に値を渡す

set dir=path/to
powershell -Command "ls %dir%"

dir 変数がコマンドプロンプト上で展開されて powershell に渡されます。

ダブルクオートのエスケープ

set data=hello
set script=Invoke-RestMethod -Uri "http://example.com" -Method POST -Body "%data%"

こんな場合、 powershell -Command に渡して実行するにはダブルクオートで実行するスクリプトを囲む必要がありますが、 "http://example.com" が存在するのでエスケープする必要があります。

重要なのはコマンドプロンプト側でエスケープすることです。

コマンドプロンプトのエスケープ文字はバックスラッシュ \ ですが、 PowerShell のエスケープ文字はバッククオート ` なので、注意が必要です。

手作業でエスケープするのは面倒なので自動的に行います。

set script=%script:"=\"%

ダブルクオートをエスケープされたダブルクオートに置換します。
そして、 PowerShell に渡す際にダブルクオートで囲みます。

powershell -Command "%script%"
30
30
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
30
30