The PSCredential object is an extremely common object in PowerShell but requires the use of the
Get-Credential command which is interactive. We can create a PSCredential object non-interactively to create these objects inside of our PowerShell scripts!
Normally, when you need to create a PSCredential object, you'll use the
Get-Credential command like
$cred = Get-Credential. This command pops up a window and asks you for a username and password. When you click OK, the command then returns the PSCredential object thus saving it to the
$cred variable in this case. However, it's interactive. That's a problem. We need to run PowerShell scripts non-interactively so we don't have to sit at the console waiting for this to come up.
Instead of using the
Get-Credentialcommand to get a PSCredential object, we can create the object from scratch using the
New-Object command. The
New-Object command allows us to pass a username and password (stored as a secure string) to it non-interactively.
For example, let's say I have a username of
admin and a password of
Sup3rSecret! that I'd like to create a PSCredential object from. To do that, I first need to convert a plaintext password (stored as a string) to a secure string. I can do this conversion using the
ConvertTo-SecureString command by passing the password and using the
Force parameters to override the warnings that plaintext passwords are a no no. Note that you can do one better by saving the credential encrypted using
Import-CliXml. You can find more information about this trick on Jaap Brasser's blog post entitled Quickly and securely storing your credentials – PowerShell.
$securePassword = ConvertTo-SecureString 'Sup3rSecret!' -AsPlainText -Force
Once I have the password stored as a secure string, I can then pass that username and password as arguments to the
PSCredential .NET class that
New-Object creates an instance of.
$cred = New-Object System.Management.Automation.PSCredential ('admin', $securepassword)
You're now able to use the
$credvariable on any cmdlet or function parameter typically called