Save Credentials to File in PowerShell
- Ben Liebowitz
Have you ever wanted to schedule a script to run overnight but need to pass secure credentials? You may do it once in open-text, but after that you say to yourself… There has to be a more secure way! Well, you were right!
See how I saved my credentials to a file to use later. Remember, you need to remember to update this each time your password changes!
First, we need to store the credentials in a variable. I’m using the variable $creds (short for credentials).
$creds = get-credential
Now, you can export those credentials to a file.
$creds | Export-Clixml -Path C:\ben\ben.cred
If you open the .cred file, you’ll see the password is ENCRYPTED and not stored in open text.
<Objs Version="184.108.40.206" xmlns="http://schemas.microsoft.com/powershell/2004/04"> <Obj RefId="0"> <TN RefId="0"> <T>System.Management.Automation.PSCredential</T> <T>System.Object</T> </TN> <ToString>System.Management.Automation.PSCredential</ToString> <Props> <S N="UserName">LAB\ben</S> <SS N="Password">01000000d08c9ddf0115d1118c7a00c04fc297eb01000000bd02a1a498abfe478b7d44a850d6382b0000000702000000000003660000c000000010000000ebd4a492452b1a9945a94b622931f13200000000a4800000a0000000100000003cc11af92858c65696e1333a743f864d300000006fed165160a77598d7bc53u3dfd28684b47402712c21f2cefd2435h12e7fef1d87ccce0eac554573d30c9b629ec89f5883140000007d1ddc030547677827ddc39cba02eb8fb969d9a1</SS> </Props> </Obj> </Objs>
Now, whenever you want to call on these credentials in a script or just in a PS window, you can just do this.
$creds = Import-Clixml -Path C:\ben\ben.cred Connect-VIServer vcsa.lab.local -credentials $creds
Of course, you can also use the New-VICredentialStoreItem cmdlet to save your credentials for that target.
New-VICredentialStoreItem -Host vcsa.lab.local -User lab\ben -Password ********
Now, whenever you want to connect to your vCenter, you don’t have to pass credentials, as they’re stored in the PowerCLI Credential Store.
I hope this helps someone!
Ben Liebowitz, VCP, vExpert
NJ VMUG Leader