I have a simple script:
$ErrorPreference = 'Stop'
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
if ($null -eq $user) {
throw 'User and password are required'
} else {
$password = (Get-Credential -credential $user).Password
if ($null -eq $password) {
throw 'Password is required'
} else {
$plainpassword = [System.Net.NetworkCredential]::new("", $password).Password
$service = Get-WMIObject -class Win32_Service -filter "name='myservice'"
if ($null -ne $service) {
[void]$service.change($null, $null, $null, $null, $null, $false, $user, $plainpassword)
} else {
throw 'Service was not installed properly'
}
}
}
and when I press "Cancel" in the dialog of credentials input, then the user and password must be $null
. So, I test them on $null
. But I get an error:
Get-Credential : Cannot bind argument to parameter 'Credential' because it is null.
At C:....ps1:6 char:45
+ $password = (Get-Credential -credential $user).Password
+ ~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Credential], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetCredenti
alCommand
Password is required
At C:....ps1:8 char:9
+ throw 'Password is required'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Password is required:String) [], RuntimeException
+ FullyQualifiedErrorId : Password is required
and I see throw 'Password is required'
but at the same time I see:
Get-Credential : Cannot bind argument to parameter 'Credential' because it is null.
and I expect that if $user
is $null
then it should not happen and I would exit before this line even. Why this happen and how to handle this?
PS. It seems $ErrorPreference = 'Stop'
is redundant, just to be sure...