Exporting and Importing Credentials

by Dec 8, 2009

You may have to use alternate credentials when you connect to different systems. You’ll find that a lot of cmdlets provide the -credential parameter, which accepts a credential object. Normally, you would create such an object by using Get-Credential and then interactively entering User Name and Password.

Use these two functions if you'd like to save your credential to file and re-use this saved version for unattended scripts:

function export-credential($cred, $path) {
$cred = $cred | Select-Object *
$cred.password = $cred.Password | ConvertFrom-SecureString
$cred | Export-Clixml $path
}
function Import-credential($path) {
$cred = Import-Clixml $path
$cred.password = $cred.Password | ConvertTo-SecureString
New-Object system.Management.Automation.PSCredential(
$cred.username, $cred.password)
}

Export-Credential can save a credential to xml:

Export-Credential (Get-Credential) c:\cred.xml

Whenever you need to use this credential, you should import it:

Get-WMIObject Win32_BIOS -computername server1 `
-credential (Import-Credential c:\cred.xml)

Note that your Password is encrypted and can only be imported by the same user that exported it.

Twitter This Tip! ReTweet this Tip!