powershellazureazure-automationpowershell-workflow

Determine if a .pfx file needs a password before calling Add-AzureCertificate


I am using the following code to install a .pfx file on an Azure Cloud Service:

Add-AzureCertificate -serviceName $CloudServiceName -certToDeploy $PfxFile.FullName -ErrorAction 'Stop' -Password $applicationCertsPassword

I think it's throwing an Exception because the .pfx file does not require a password.

How can I determine beforehand whether or not the .pfx file requires a password?

EDIT: I'd like to determine beforehand if the .pfx file has a password or not so I can avoid running the commandlet again without the password argument in the catch block.


Solution

  • You could always put it in a Try{} and then do the same command without the password in the Catch{}, but that's kind of dirty scripting.

    Try{
        Add-AzureCertificate -serviceName $CloudServiceName -certToDeploy $PfxFile.FullName -ErrorAction 'Stop' -Password $applicationCertsPassword
    }
    Catch{
        Add-AzureCertificate -serviceName $CloudServiceName -certToDeploy $PfxFile.FullName -ErrorAction 'Stop'
    }
    

    What I think I would probably do instead is attempt to load the certificate up as an object with no password, and if that fails I'd know that there's a password for it.

    $OldEA = $ErrorActionPreference
    $ErrorActionPreference = SilentlyContinue
    If([System.Security.Cryptography.X509Certificates.X509Certificate2]::CreateFromCertFile($pfxfile.fullname)){"No Password"}
    $ErrorActionPreference = $OldEA
    

    Pretty sure that'll accomplish what you want. I don't happen to have a PFX file without a password to verify with right now though, because as Jan pointed out they aren't really something you should have in general.