Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill the prompt in powershell script

Tags:

powershell

I use a command like this:

get-pfxcertificate C:\test.pfx

Enter password: *******

The command ask me to fill the prompt. But I can't do that in my script (test.ps1 for ex)

What I need is like this:

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

or something similar so I can run my script without fill in the prompt each time

I'm very thankful for any reply

like image 462
Tran Ngu Dang Avatar asked Dec 27 '12 03:12

Tran Ngu Dang


2 Answers

There's no Password parameter, you can try with a .NET class:

$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import('C:\test.pfx','123456','DefaultKeySet')
like image 125
Shay Levy Avatar answered Oct 24 '22 14:10

Shay Levy


Another option is to extend the abilities of Get-PfxCertificate, essentially enabling the password to be passed in.

# 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
}

And now you can call it

# tada: extended cmdlet with `password` parameter
Get-PfxCertificate 'C:\path\to\cert.pfx' 'password'

Also, if you still need the prompt, you can do something like this.

$pwd = Read-Host 'Please enter your SSL Certificate password.'
Get-PfxCertificate 'C:\path\to\cert.pfx' $pwd
like image 35
Chase Florell Avatar answered Oct 24 '22 14:10

Chase Florell