スクリプト実行ポリシー

スクリプトの実行ポリシーを設定することで、スクリプト実行時の挙動を制御します

PowerShellでは、セキュリティが理由でデフォルトではスクリプトを実行できない状態(Restricted)になっている場合があります。
そのため、スクリプトを実行したければ実行ポリシーを変更する必要があります。
また、実行ポリシーを変更する際にスコープ(適応範囲)を指定できます。

Microsoft Docs
実行ポリシーについて
https://docs.microsoft.com/ja-jp/previous-versions/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.0

Example スクリプト実行ポリシーを変更する

Restricted状態でエラーになり、
カレントユーザの実行ポリシーをRemoteSignedに変更し、
スクリプトを実行する例。

PS C:\Users\user\Desktop> Get-ExecutionPolicy
Restricted
PS C:\Users\user\Desktop> .\script.ps1
# エラーになる
 
PS C:\Users\user\Desktop> Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
 
Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
you to the security risks described in the about_Execution_Policies help topic at
http://go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): y
PS C:\Users\user\Desktop> Get-ExecutionPolicy
RemoteSigned
PS C:\Users\user\Desktop> .\script.ps1
Hello!

一時的に実行ポリシーを変更する

PowerShellを実行する時に「-ExecutionPolicy」をつけると、一時的に実行ポリシーを変更できます。

cmd> powershell script.ps1
# エラーになる
 
cmd> powershell -ExecutionPolicy RemoteSigned .\script.ps1
Hello!
 
cmd> powershell .\script.ps1
# エラーになる

YouTube


スポンサーリンク