整体运行PowerShell脚本不起作用,但可以批量运行

时间:2019-02-15 06:28:58

标签: powershell ssl-certificate

同时运行以下脚本(作为ps1文件)不能正确设置私钥的权限,并且当我导航到管理证书上的私钥时会出现此错误。

Error

但是,如果我以相同的顺序运行所有命令,但以小批量运行,则可以看到私钥权限,而不能像一起运行时一样看到错误。大批量运行(3个单独的命令)也不起作用,因此不要认为它是命令行/文件内容

我在做什么错了?

Import-Module WebAdministration

# Delete current certificates
Remove-Item cert:\LocalMachine\Root\asdfasdfadfasf
Remove-Item cert:\LocalMachine\My\asdfasdfadfasf -DeleteKey

# Add the new certificate to the correct stores
$certBytes = [System.Convert]::FromBase64String("cert as base 64")
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certBytes, "password", "MachineKeySet,PersistKeySet")
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My", "LocalMachine")
$store.Open("ReadWrite")
$store.Add($cert)
$store.Close()
$store2 = New-Object System.Security.Cryptography.X509Certificates.X509Store("Root", "LocalMachine")
$store2.Open("ReadWrite")
$store2.Add($cert)
$store2.Close()

# Get the certificate added above
$certificate = Get-ChildItem "Cert:\LocalMachine\My" |
               Where thumbprint -eq "asdfasdfadfasf"
if ($certificate -eq $null) {
    $message = "Certificate with thumbprint:asdfasdfadfasf does not exist at Cert:\LocalMachine\My"
    Write-Host $message -ForegroundColor Red
    exit 1;
} else {
    # Get the private key permissions
    $rsaCert = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate)
    $fileName = $rsaCert.key.UniqueName
    $path = "$env:ALLUSERSPROFILE\Microsoft\Crypto\RSA\MachineKeys\$fileName"
    $permissions = Get-Acl -Path $path

    #  Get the appPool user
    $site = Get-IISSite -Name 'website'
    $appPool = Get-IISAppPool -Name $site.Applications[0].ApplicationPoolName
    $appPoolUser = "IIS AppPool\"+$appPool.Name

    # Give read permissions on the private key
    $access_rule = New-Object System.Security.AccessControl.FileSystemAccessRule($appPoolUser, 'Read', 'None', 'None', 'Allow')
    $permissions.AddAccessRule($access_rule)
    Set-Acl -Path $path -AclObject $permissions
}

0 个答案:

没有答案