Trevor Sullivan Trevor Sullivan - 4 months ago 47
Powershell Question

Create a PSCredential with empty username

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?

Answer

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.

Comments