导入 PfxCertificate returns FileNotFoundException

Import-PfxCertificate returns FileNotFoundException

我正在尝试将单个自签名证书分发到多个服务器,分发到一组服务帐户的个人证书存储中。此证书将用于解密只有服务帐户才能读取的敏感文件。

证书创建如下:

New-SelfSignedCertificate -DnsName CredentialVault `
    -CertStoreLocation "Cert:\CurrentUser\My" `
    -KeyUsage KeyEncipherment,DataEncipherment -Type DocumentEncryptionCert `
    -KeyAlgorithm RSA -KeyLength 2048 
$computer = 'SERVER123.EXAMPLE.COM'
$cred = New-Object PSCredential 'MYDOMAIN\USER213', `
            $(ConvertTo-SecureString -String 'P4$$w0Rd' -AsPlainText -Force)

$scriptBlock = {
    Import-PfxCertificate -FilePath 'C:\temp\CredentialVault.pfx' `
        -Password $(ConvertTo-SecureString -String '1234' -AsPlainText -Force) `
        -CertStoreLocation "Cert:\CurrentUser\My"
}

Invoke-Command -ComputerName $computer -Credential $cred -ScriptBlock $scriptBlock 

我在服务器 SERVER123.EXAMPLE.COM 上执行代码(但使用不同的帐户),只是想在尝试远程服务器之前看看它是否能正常工作。这就是文件路径引用本地文件的原因。

但是,即使 MYDOMAIN\USER213 帐户可以访问该文件(我首先在与该用户相同的服务器上直接测试了 Import-PfxCertificate 命令),PowerShell returns System.IO.FileNotFoundException 如下所示。

The PFX file could not be found.
    + CategoryInfo          : NotSpecified: (:) [Import-PfxCertificate], FileNotFoundException
    + FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.CertificateServices.Commands.ImportPfxCertificate
    + PSComputerName        : SERVER123.EXAMPLE.COM

我不知道问题出在哪里。欢迎提出建议!

版本信息:

可能你必须尝试在路径中使用变量$env:HOMEDRIVE\temp\CredentialVault.pfx

我最终通过 PSSession 将文件复制到远程系统解决了这个问题。

仍然不知道为什么这行得通,而原始代码却行不通。 ¯\_(ツ)_/¯

$certFile = 'C:\temp\CredentialVault.pfx'
$remoteFile = [System.IO.Path]::Combine('C:\Temp', [System.IO.Path]::GetFileName($certFile))
$certPassword = $(ConvertTo-SecureString -String '1234' -AsPlainText -Force)
$cred = Get-Credential

$sess = New-PSSession -ComputerName $server -Credential $cred
try {
    Copy-Item -Path $certFile -ToSession $sess -Destination $remoteFile
    Invoke-Command -Session $sess -ScriptBlock {
        Import-PfxCertificate -FilePath $remoteFile `
                              -Password $certPassword `
                              -CertStoreLocation "Cert:\CurrentUser\My"
        Remove-Item $remoteFile
    }
}
finally {
    Remove-PSSession $sess
}