如何填写powershell脚本中的提示

Tra*_*ang 4 powershell

我使用这样的命令:

get-pfxcertificate C:\test.pfx

Enter password: *******

该命令要求我填写提示.但我不能在我的脚本中执行此操作(test.ps1 for ex)

我需要的是这样的:

get-pfxcertificate C:\test.pfx -password "123456"

或类似的东西,所以我可以运行我的脚本,而不是每次都填写提示

我非常感谢任何回复

Sha*_*evy 14

没有Password参数,您可以尝试使用.NET类:

$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import('C:\test.pfx','123456','DefaultKeySet')
Run Code Online (Sandbox Code Playgroud)


Cha*_*ell 6

另一种选择是扩展功能Get-PfxCertificate,基本上可以传入密码.

# create a backup of the original cmdlet
if(Test-Path Function:\Get-PfxCertificate){
    Copy Function:\Get-PfxCertificate Function:\Get-PfxCertificateOriginal
}

# create a new cmdlet with the same name (overwrites the original)
function Get-PfxCertificate {
    [CmdletBinding(DefaultParameterSetName='ByPath')]
    param(
        [Parameter(Position=0, Mandatory=$true, ParameterSetName='ByPath')] [string[]] $filePath,
        [Parameter(Mandatory=$true, ParameterSetName='ByLiteralPath')] [string[]] $literalPath,

        [Parameter(Position=1, ParameterSetName='ByPath')] 
        [Parameter(Position=1, ParameterSetName='ByLiteralPath')] [string] $password,

        [Parameter(Position=2, ParameterSetName='ByPath')]
        [Parameter(Position=2, ParameterSetName='ByLiteralPath')] [string] 
        [ValidateSet('DefaultKeySet','Exportable','MachineKeySet','PersistKeySet','UserKeySet','UserProtected')] $x509KeyStorageFlag = 'DefaultKeySet'
    )

    if($PsCmdlet.ParameterSetName -eq 'ByPath'){
        $literalPath = Resolve-Path $filePath 
    }

    if(!$password){
        # if the password parameter isn't present, just use the original cmdlet
        $cert = Get-PfxCertificateOriginal -literalPath $literalPath
    } else {
        # otherwise use the .NET implementation
        $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
        $cert.Import($literalPath, $password, $X509KeyStorageFlag)
    }

    return $cert
}
Run Code Online (Sandbox Code Playgroud)

现在你可以打电话给它

# tada: extended cmdlet with `password` parameter
Get-PfxCertificate 'C:\path\to\cert.pfx' 'password'
Run Code Online (Sandbox Code Playgroud)

此外,如果您仍需要提示,则可以执行此类操作.

$pwd = Read-Host 'Please enter your SSL Certificate password.'
Get-PfxCertificate 'C:\path\to\cert.pfx' $pwd
Run Code Online (Sandbox Code Playgroud)


Sun*_*000 6

PowerShell 中现在有一个Get-PfxData命令可以获取证书和链。该命令包含一个-Password采用 SecureString 对象的参数,这样您就可以避免收到提示。

EndEntityCertificates属性包含证书链末尾的证书数组,并将包含由该Get-PfxCertificate命令创建的相同证书对象。

以下示例将普通字符串转换为 SecureString 对象,从文件加载证书,然后将第一个/唯一的结束证书分配给 $SigningCert 变量:

$SecurePassword=ConvertTo-SecureString -String "MyPassword" -AsPlainText -Force
$PfxData=Get-PfxData -FilePath ".\cert_filename.pfx" -Password $SecurePassword
$SigningCert=$PfxData.EndEntityCertificates[0]
Run Code Online (Sandbox Code Playgroud)

您现在可以应用 $SigningCert,而无需提示输入密码。