PowerShellに署名をつける
自己署名証明書の作成と設定
MyCertという名前で証明書を作成し、RootとTrustedPublisherに証明書を追加します。 また、デスクトップに、MyCert.cerという名前でエクスポートします。
なお、ユーザー証明書ではなく、システム証明書として登録する場合は、cert:\CurrentUser\
をすべてcert:\LocalMachine\
に置き換えてください。
$CertName = "MyCert" $CertPath = "${env:userprofile}\Desktop\$CertName.cer" $Cert = New-SelfSignedCertificate ` -Type CodeSigningCert ` -CertStoreLocation "cert:\CurrentUser\My" ` -Subject $CertName ` -KeyAlgorithm RSA ` -KeyLength 2048 ` -KeyExportPolicy Exportable ` -NotAfter (Get-Date).AddYears(1).AddMonths(6) Get-ChildItem -Path "cert:\CurrentUser\My\" | Where-Object {$_.Subject -eq "CN=$CertName"} | Export-Certificate -FilePath $CertPath -Type CERT Import-Certificate -FilePath $CertPath -CertStoreLocation "cert:\CurrentUser\Root" Import-Certificate -FilePath $CertPath -CertStoreLocation "cert:\CurrentUser\TrustedPublisher"
PowerShellスクリプトへの署名
先ほど作成したMyCertでscript.ps1というPowershellスクリプトに署名を行います。
注意点として、同名の証明書が複数ある場合は、下記のスクリプトで適切な証明書が選択できないため、Certification Managerから対象の証明書のFingerPrintを調べ、Set-AuthenticodeSignatureコマンドで署名を行ってください。
$CertName = "MyCert" $ScriptPath = "script.ps1" $Cert = Get-ChildItem -Path "cert:\CurrentUser\My\" | Where-Object {$_.Subject -eq "CN=$CertName "} Set-AuthenticodeSignature $ScriptPath $Cert
テスト
ポリシーをAllSignedにしたPowershellのプロセスでスクリプトが実行されることを確認します。 動作すれば署名が正しくできています。
$ScriptPath = "script.ps1" powershell -ExecutionPolicy AllSigned $ScriptPath
他の環境での実行
エクスポートした証明書をRootとTrustedPublisherにインポートしてください。 証明書を対象のマシンにコピーしてGUI、もしくは下記のコマンドでインポート可能です。
$CertPath = "MyCert.cer" Import-Certificate -FilePath $CertPath -CertStoreLocation "cert:\CurrentUser\Root" Import-Certificate -FilePath $CertPath -CertStoreLocation "cert:\CurrentUser\TrustedPublisher"