I need to create a PSCredential with an empty username.
$Password = ConvertTo-SecureString -AsPlainText -Force -String 'a'
$Credential = New-Object -TypeName PSCredential -ArgumentList '', $Password
When I run the above code, I get an exception.
New-Object : Exception calling ".ctor" with "2" argument(s): "Cannot process argument because the value of argument "userName" is not valid. Change the value of the "userName" argument and run the operation again."
How can I create a PSCredential with an empty username, and only have a password?
As you've discovered (and as Ansgar Wiechers notes in a comment on the question), you cannot directly provide an empty username (empty string or $null
) to the [System.Management.Automation.PSCredential]
constructor that accepts username and password separately.
You can work around that problem by using the constructor that accepts a [psobject]
instance, by passing a custom object ([pscustomobject]
instance) with UserName
and Password
properties (PSv3+):
$Credential = New-Object PSCredential -ArgumentList ([pscustomobject] @{
UserName = '';
Password = (ConvertTo-SecureString -AsPlainText -Force -String 'a')[0]
})
Note the [0]
applied to the result of the ConvertTo-SecureString
call, which is required for the output object to be properly recognized as a [securestring]
([System.Security.SecureString]
) instance (this trick is not needed if you use an intermediate variable, as in the question). I'm not exactly sure why this is necessary; perhaps the output is by default treated as a collection here; if you know specifically, do tell us.
Caveats:
Given that the two constructor forms set the same data fields, the ability to set an empty username with the object-based constructor could be a bug that may get fixed in the future - I don't know what the intended behavior is.
I'm unclear on whether the resulting credential object works as intended.
For instance, $Credential.GetNetworkCredential()
fails in the absence of a username.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With