Exporting and Importing Credentials in PowerShell

by Mar 28, 2014

Credential objects contain a username and a password. You can create them using Get-Credential, and then supply this object to any cmdlet that has the -Credential parameter.

However, what do you do if you want your scripts to run without user intervention yet securely? You do not want a credentials dialog to pop up, and you do not want to store the password information inside the script.

Here's a solution: use the function Export-Credential to save the credential to file:

function Export-Credential 
{
   param
   (
     [Parameter(Mandatory=$true)]
     $Path,

     [System.Management.Automation.Credential()]
     [Parameter(Mandatory=$true)]
     $Credential
   )
    
  $CredentialCopy = $Credential | Select-Object *    
  $CredentialCopy.Password = $CredentialCopy.Password | ConvertFrom-SecureString    
  $CredentialCopy | Export-Clixml $Path
} 

This would save a credential for the user tobias to a file:

Note that while you do this, the credentials dialog pops up and securely asks for your password. The resulting file contains XML, and the password is encrypted.

Now, when you need the credential, use Import-Credential to get it back from file:

function Import-Credential 
{
   param
   (
     [Parameter(Mandatory=$true)]
     $Path
   )
    
  $CredentialCopy = Import-Clixml $path    
  $CredentialCopy.password = $CredentialCopy.Password | ConvertTo-SecureString    
  New-Object system.Management.Automation.PSCredential($CredentialCopy.username, $CredentialCopy.password)
}

So use it like this:

The "secret" used for encryption and decryption is your identity, so only you (the user that exported the credential) can import it again. No need to hard-code secrets into your script.

Twitter This Tip! ReTweet this Tip!