首页 > 解决方案 > Import-PfxCertificate 返回 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 仍会返回 a 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

我不知道问题是什么。欢迎提出建议!

版本信息:

标签: powershellcertificate

解决方案


我最终通过首先将文件复制到远程系统来解决它,通过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
}

推荐阅读