概要
Windows PowerShellではセキュリティのために、実行ポリシーによってスクリプトの実行がブロックされている。
そのため、PowerShellのスクリプトを実行する場合、一時的に実行ポリシーを変更する必要がある。
スクリプトのサンプル
実行ポリシーを変更前と変更後で以下のスクリプトを実行してどのような挙動となるか確認する。
# example.ps1
Write-Output 'hoge'
スクリプトの実行が制限されている場合
-
Windows PowerShellを起動する。
-
現在の実行ポリシーを確認する。
- 全ての実行ポリシーが未定義(初期状態)
PS C:\xxxxx\Desktop> Get-ExecutionPolicy -List Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser Undefined LocalMachine Undefined -
PowerShellスクリプトを実行する
- スクリプトを実行時にエラーとなる。
PS C:\xxxxx\Desktop> .\example.ps1 .\example.ps1 : このシステムではスクリプトの実行が無効になっているため、ファイル C:\xxxxx\Desktop\example.ps1 を読み込むことができません。詳細については、「about_Execution_Policies」(https://go.microsoft.com/fwlink/?LinkID=135170)を参照してください。
スクリプトの実行ポリシーを一時的に変更する
-
Windows PowerShellを起動する。
-
現在のPowerShellプロセスに限り、実行ポリシーを変更する。
-
-Scope Process:- 現在のPowerShellウィンドウを閉じるまで。
-
RemoteSigned:- ローカルで作成したスクリプトは署名なしで実行可能
- インターネットからダウンロードしたスクリプトは信頼できる発行元による署名が必要
PS C:\xxxxx\Desktop> Set-ExecutionPolicy RemoteSigned -Scope Process -
-
実行ポリシーを確認する。
- Processに実行ポリシーが設定されている。
PS C:\xxxxx\Desktop> Get-ExecutionPolicy -List Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process RemoteSigned CurrentUser Undefined LocalMachine Undefined -
再度、PowerShellスクリプトを実行してみる。
- スクリプトを実行できる。
PS C:\xxxxx\Desktop> .\example.ps1 hoge