Errors when cancel Get-Credential

I’ve been working with the Get-Credential commandlet in PowerShell, and it mostly works for me.

However, when I select Cancel, the “corner X” or Esc to cancel without entering anything, I get several red lines of error stuff about missing parameters and such.
This is before I do any processing, I just want to catch that the user canceled out of the operation without entering anything in the fields.

I have searched and tested to no avail. Can someone tell me how to suppress the error stuff (i already know that I didn’t enter any parameters) so I can just bail out of the script?

Specifically, this is what I get:

Get-Credential : Cannot process command because of one or more missing mandatory parameters: Credential.
At C:\utils\validator.ps1:15 char:12

  • $OpCreds = Get-Credential #Read credentials
  •        ~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidArgument: (:slight_smile: [Get-Credential], ParameterBindingException
    • FullyQualifiedErrorId : MissingMandatoryParameter,Microsoft.PowerShell.Commands.GetCredentialCommand

You cannot call a method on a null-valued expression.
At C:\utils\validator.ps1:17 char:2

  • $password = $OpCreds.GetNetworkCredential().password
  •  + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
     + FullyQualifiedErrorId : InvokeMethodOnNull
    

Here’s the associated PS code:

$OpCreds = Get-Credential #Read credentials
if ($OpCreds -eq $null) { EXIT }
$username = $OpCreds.username
$password = $OpCreds.GetNetworkCredential().password

$CurrentDomain = “LDAP://” + ([ADSI]“”).distinguishedName
$domain = New-Object System.DirectoryServices.DirectoryEntry($CurrentDomain,$UserName,$Password)

Thanks!

Wrap your …

… in a try block and specify in the catch block what you want to do in case of an error. :man_shrugging:t3:

It seems that putting $null -eq $0pCreds is preferable over the opposite.

Here’s the updated code with no errors when you click cancel on the credential prompt.

try {
    $OpCreds = Get-Credential -ErrorAction SilentlyContinue
} catch {
	if ($null -eq $OpCreds) { 
        Write-Host "User Cancelled"
        exit
    }
}
$username = $OpCreds.username
$password = $OpCreds.GetNetworkCredential().password

Thank you, thank you! This worked perfectly.

Your help is appreciated!

—K