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: ( [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!