从头到尾创建自签名 PowerShell 脚本

Creating self-signed PowerShell scripts start to finish

在我自己调查这个问题时,我无法找到关于自签名 PowerShell 脚本的任何从头到尾的解决方案。那么,您如何在 PowerShell 本身中处理所有独立的问题以利用 AllSigned 执行策略并帮助更好地保护您的系统?

这是一种现代的自签名 PowerShell 脚本方法。我发现旧版本的 PowerShell ISE(仅确认为 2.0)将使用 Big Endian 与 UTF-8 对您的脚本进行编码,并导致签名问题。使用这种方法,你不应该 运行 因为我们在这里使用 v4+。
要求:PoSH 4.0+.

此函数将:检查 Pfx 证书是否存在并将其导入 LocalMachine\TrustedPublisher;检查证书是否传递给它,导出到 Pfx 证书并导入它;或创建 LocalMachine\Personal 的证书,将其导出并导入。我无法获得与我一起使用 \My(个人)之外的 Cert:\CurrentUser 商店的权限。

$ErrorActionPreference = 'Stop'

Function New-SelfSignedCertificate
{
    Param([Parameter(Mandatory=$True)]$PfxCertPath,$CertObj)

    # Creates a SecureString object
    $Cred = (Get-Credential).Password

    If (Test-Path $PfxCertPath)
    {
        Try {
          Import-PfxCertificate -FilePath $PfxCertPath -Password $Cred -CertStoreLocation Cert:\LocalMachine\TrustedPublisher
          Write "$($PfxCertPath.FriendlyName) exists and is valid. Imported certificate to TrustedPublishers"
        } Catch {
          Write "Type mismatch or improper permission. Ensure your PFX cert is formed properly."
          Write "[$($_.Exception.GetType().FullName)] $($_.Exception.Message)"
        }
    } ElseIf ($CertObj) {
        Try {
          Export-PfxCertificate -Cert $CertObj -FilePath $PfxCertPath -Password $Cred -Force
          Import-PfxCertificate -FilePath $PfxCertPath -Password $Cred -CertStoreLocation Cert:\LocalMachine\TrustedPublisher
        } Catch {
          Write "[$($_.Exception.GetType().FullName)] $($_.Exception.Message)"
        }
    } Else {
        Try {
          $DNS = "$((GWMI Win32_ComputerSystem).DNSHostName).$((GWMI Win32_ComputerSystem).Domain)"
          $CertObj = New-SelfSignedCertificate -CertStoreLocation Cert:\LocalMachine\My -DnsName $DNS -Type CodeSigningCert -FriendlyName 'Self-Sign'
          Export-PfxCertificate -Cert $CertObj -FilePath $PfxCertPath -Password $Cred -Force
          Import-PfxCertificate -FilePath $PfxCertPath -Password $Cred -CertStoreLocation Cert:\LocalMachine\TrustedPublisher
        } Catch {
          Write "[$($_.Exception.GetType().FullName)] $($_.Exception.Message)"
        }
    }
}

# Can be called like:
#   Sign-Script -File C:\Script.ps1 -Certificate (GCI Cert:\LocalMachine\TrustedPublisher -CodeSigningCert)
#
# After the cert is imported to TrustedPublisher, you can use the
# exported pfx cert to sign on the machine instead of this method
Function Sign-Script
{
    Param($File,$Cert)
    If($Cert-is[String]){Try{$Cert=Get-PfxCertificate("$Cert")}Catch{}}
    Set-AuthenticodeSignature -FilePath $File -Certificate $Cert -Force
}
Function Check-SignedScript
{
    Param($File)
    Get-AuthenticodeSignature -FilePath $File 
}

说完一切后,您可以以管理员身份执行 Set-ExecutionPolicy AllSigned 并使用此脚本对所有脚本进行签名。 Check-SignedScript 会告诉您符号是否有效,您可以判断 Sign-Script 是否有效,因为您的文件末尾会有 # SIG # Begin signature block。对已签名脚本的任何编辑都需要重新签名才能执行。