【Windows】PowerShell_実行エラー(about_Execution_Policies)

PowerShell

はじめに

PowerShellを実行しようとすると、以下のようなエラーが発生する事があります。

PS C:\Windows\system32> C:\work\01_create-user-wg.ps1
このシステムではスクリプトの実行が無効になっているため、ファイル C:\work\01_create-user-wg.ps1 を読み込むことができません。詳細については、「about_Execution_Policies」(https://go.microsoft.com/fwlink/?LinkID=135170) を参照してください。
    + CategoryInfo          : セキュリティ エラー: (: ) []、ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnauthorizedAccess

「何これ?」と最初は思うものの、エラーの案内にある以下のページを参照すればおおよそ解決方法が見えてきます。

about_Execution_Policies - PowerShell
Describes the PowerShell execution policies and explains how to manage them.

とはいえ、毎回見るのも面倒になってきたので、以下備忘録兼忙しい人用に解決策だけ書いておきます。

解決策

まず現在の設定を確認してします。「Restricted」になっているとエラーになります。

PS C:\Windows\system32> Get-ExecutionPolicy
Restricted

参考に、設定一覧を見ます。これは省略可能です。

PS C:\Windows\system32> Get-ExecutionPolicy -List

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser       Undefined
 LocalMachine       Undefined

以下のコマンドを実行します。質問に対して「A」を回答します。

PS C:\Windows\system32>  Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

実行ポリシーの変更
実行ポリシーは、信頼されていないスクリプトからの保護に役立ちます。実行ポリシーを変更すると、about_Execution_Policies
のヘルプ トピック (https://go.microsoft.com/fwlink/?LinkID=135170)
で説明されているセキュリティ上の危険にさらされる可能性があります。実行ポリシーを変更しますか?
[Y] はい(Y)  [A] すべて続行(A)  [N] いいえ(N)  [L] すべて無視(L)  [S] 中断(S)  [?] ヘルプ (既定値は "N"):
※Aを選択

GUIの場合。

最後に念のため現在の設定を確認しておきます。

PS C:\Windows\system32>> Get-ExecutionPolicy
RemoteSigned

以上です。