Getting the Password Value from PSCredential objects
PowerShell PSCredential objects are probably the best way to use credentials within PowerShell and protect the password. There's a catch however when it comes to the need to have the password saved in the object in plain text format in order to use it where the object is not acceptable as input. Take for example a connection to a SQL server where a connection string is required. Below is the way to extract the password.
We'll start of by creating a PSCredential object to use as example:
As you may see on the output of the command, the "Password" property is an object of type SecureString.
Fortunatelly, the PSCredential object has a method that can provide the plain text value of the password.
By using the GetNetworkCredential method, we have access to the username and password in plain text format:
We can now use the PSCredential object to construct any connection strings or login to services using the password provided.
We'll start of by creating a PSCredential object to use as example:
PS C:\> $cred = Get-Credential
PS C:\Users\cpolydorou> $cred
UserName Password
-------- --------
testuser System.Security.SecureString
PS C:\Users\cpolydorou> $cred
UserName Password
-------- --------
testuser System.Security.SecureString
As you may see on the output of the command, the "Password" property is an object of type SecureString.
Fortunatelly, the PSCredential object has a method that can provide the plain text value of the password.
By using the GetNetworkCredential method, we have access to the username and password in plain text format:
PS C:\> $cred.GetNetworkCredential().Username
testuser
PS C:\> $cred.GetNetworkCredential().Password
testpassword
testuser
PS C:\> $cred.GetNetworkCredential().Password
testpassword
We can now use the PSCredential object to construct any connection strings or login to services using the password provided.