Get-Credential No Longer Prepends Username With a Backslash in PowerShell v3

This one tripped me up earlier in the week, so thought it was worth sharing in case you hit the same issue sometime. In PowerShell v2 and earlier when using Get-Credential to save credentials into a variable and NOT using a full Windows domain credential, e.g. something like:


instead of a more Windows style credential:


then the resultant stored credential prepends a \ in front of the username:

$cred = Get-Credential

PS C:\\> $cred

UserName Password -------- -------- \\root System.Security.SecureString

PS C:\\> $cred.UserName.Length 5

This doesn’t cause any issues when working with the credential object, for instance to connect directly to an ESXi host instead of to vCenter using the credential object with root as the username.

Connect-VIServer ESXi01 -Credential $cred

However, if you need to pick out the username from the credential object and use it for something else this can be a problem. This is what I tripped over this week, not sure how I’ve never hit it before. I was taking out the username to use as part of a connection string for pscp.exe .

$ESXiUsername = $Credential.UserName $ESXiSSLPath = "$ESXiUsername@$($DNSName):/etc/vmware/ssl"

Unfortunately, this made the connection string




and so the connection failed.

You can get round this by using the TrimStart method, like in the following:

$ESXiUsername = $Credential.UserName.TrimStart('\\')

The reason I discovered this was I had written the code in PowerShell v3 and then run it from a v2 box. In v3 Get-Credential no longer prepends the \ when a non-Windows domain credential is used

$cred = Get-Credential

PS C:\\> $cred

UserName Password -------- -------- root System.Security.SecureString

PS C:\\> $cred.UserName.Length 4

I hadn’t seen any mention of this with the release and the documentation doesn’t seem to have been updated either,

“If you enter a user name without a domain, Get-Credential inserts a backslash before the name.”

so I filed a Connect item.