How to catch a bad password?

Hello,
I am trying to figure out how I can take action if a bad password is entered here:

$password  = Read-Host -Prompt "Please enter the SSL password for the certificates" -AsSecureString
        Import-PfxCertificate -FilePath "C:\Temp\somecert.pfx" -Password ($Password) -CertStoreLocation "Cert:\LocalMachine\My" -ErrorAction SilentlyContinue

If I enter wrong password, it complains of course, how can I capture that in say an If its correct move on, but if its a bad password, do something else.

Thanks!

Hmmm … I don’t know if I got what you’re actually asking. With the code snippet you poasted I’d say a try catch block and a loop should help you when the password the user provided is wrong.

For all other cases it depends pretty much on what you define as “bad password” :wink:

If you want to check the length and complexity of the input in advance you would need to use regex with an according pattern.

Hello,
This is working well, thanks:

$password  = Read-Host -Prompt "Please enter the SSL password for the certificates" -AsSecureString
        try {
        Import-PfxCertificate -FilePath "C:\Temp\somecert.pfx" -Password ($Password) -CertStoreLocation "Cert:\LocalMachine\My" -ErrorAction SilentlyContinue
        Import-PfxCertificate -FilePath "C:\Temp\someothercert.pfx" -Password ($Password) -CertStoreLocation "Cert:\LocalMachine\My" -ErrorAction SilentlyContinue
        }
        catch {
            Write-Host "Bad password entered!" -ForeGroundColor Yellow
            Remove-Item C:\Temp\somecert.pfx,C:\Temp\someothercert.pfx
            exit
            }

-Matt

If you want to allow the user to retry entering a password, you could use a do loop like this:


do {
    try {
        $password = Read-Host -Prompt "Please enter the SSL password for the certificates" -AsSecureString
        Import-PfxCertificate -FilePath "C:\Temp\somecert.pfx" -Password ($Password) -CertStoreLocation "Cert:\LocalMachine\My" -ErrorAction SilentlyContinue -ErrorAction Stop
        $Success = $true
    }
    catch {
        Write-Warning "Invalid password."
        $Success = $false
    }
} until ($Success)

1 Like

ooh I like that darwin-reiswig, thanks! Ill def try that out