2
2

More than 1 year has passed since last update.

デジタル署名できるPowerShellコマンドを用意した

Posted at

TL; DR

下記のような使い方で、 my-command.ps1 コマンドがPowerShell内で実行できるようになります。

実行例
authenticate-to-script.ps1 'PowerShell Script for my-command.ps1' .\my-command.ps1

はじめに

PowerShellスクリプトを用意するためには、デジタル署名が必要です。

スクリプトを用意するだけで、毎回上記手順が必要になると大変です。
そこで、デジタル署名用のスクリプトを用意して、スクリプト作成を簡単にしたいです。

デジタル署名用スクリプトの用意

以下手順にて、デジタル署名用スクリプトを用意します。

スクリプトファイルの用意

以下コマンドを保存したPowerShellファイルを、パスの通ったディレクトリに配置してください。

authenticate-to-script.ps1
Param(
  [parameter(mandatory=$true)][String]$Description,
  [parameter(mandatory=$true)][String]$ScriptFile
)

$ScriptFilePath = Convert-Path $ScriptFile

if ( $ScriptFilePath -ne $null )
{
  $ScriptFileFullPath = Get-Command $ScriptFilePath | select $_.FullName
  $Cert = New-SelfSignedCertificate `
    -Subject "CN=$Description, OU=Self-signed RootCA" `
    -KeyAlgorithm RSA `
    -KeyLength 4096 `
    -Type CodeSigningCert `
    -CertStoreLocation Cert:\CurrentUser\My\ `
    -NotAfter ([datetime]"2099/01/01")
  Move-Item "Cert:\CurrentUser\My\$($Cert.Thumbprint)" Cert:\CurrentUser\Root
  $RootCert = @(Get-ChildItem cert:\CurrentUser\Root -CodeSigningCert)[0]
  Set-AuthenticodeSignature $ScriptFileFullPath.Source $RootCert
}

用意したスクリプトファイルのデジタル署名

次のコマンドでデジタル署名をしてください(まだ上記スクリプトは利用できません)。

デジタル署名のコマンド
# ファイルのフルパスを取得する
$ScriptFileFullPath = Get-Command authenticate-to-script.ps1 | select $_.FullName

# 証明書を用意する
$Cert = New-SelfSignedCertificate `
  -Subject "CN=PowerShell Script for authenticate-to-script.ps1, OU=Self-signed RootCA" `
  -KeyAlgorithm RSA `
  -KeyLength 4096 `
  -Type CodeSigningCert `
  -CertStoreLocation Cert:\CurrentUser\My\ `
  -NotAfter ([datetime]"2099/01/01")

# 証明書をルートに移動する
Move-Item "Cert:\CurrentUser\My\$($Cert.Thumbprint)" Cert:\CurrentUser\Root

# ルート証明書として自己証明する
$RootCert = @(Get-ChildItem cert:\CurrentUser\Root -CodeSigningCert)[0]
Set-AuthenticodeSignature $ScriptFileFullPath.Source $RootCert

上記までで、 authenticate-to-script.ps1 が使えるようになりました。
実際に動作を確認してみてください。

もし自己証明書を消したくなったら

以下を参考にしてください。

おわりに

このコマンドを使って用意した最初のコマンドはdiff.ps1です。

2
2
1

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
2
2