Apple iTunes
 

First things first, the two functions in this article are not my original work. I found Export-PSCredential and Import-PSCredential on the poshcode.org site (see here for original article: http://poshcode.org/474 ). All the credit goes to the contributor on that site (great work by the way!) The main reasons for posting it here are: (1) I’ve made a minor change to include a -HELP parameter and (2) I find these function to be so incredibly useful that I want to make sure I have a copy posted somewhere so I don’t lose them.

Export-PSCredential

?View Code POWERSHELL
function Export-PSCredential {
    param (
        #$Credential = (Get-Credential),
        $Credential = "",
        $Path = "credentials.enc.xml",
        [switch]$Help)
 
    $HelpInfo = @'
 
    Function : Export-PSCredential
    Date     : 02/24/2011
    Purpose  : Exports user credentials to an encoded XML file. Resulting file
               can be imported using function: Import-PSCredential
    Usage    : Export-PSCredential [-Credential <[domain\]username>][-Path ][-Help]
               where
                  -Credential specify the user account for which we will create a credential file
                              password will be collected interactively
                  -Path       specify the file to which credential information will be written.
                              if omitted, the file will be "credentials.enc.xml" in the current
                              working directory.
                  -Help       displays this help information
    Note     : Import-PSCredential can be used to decode this file into a PSCredential object and
               MUST BE executed using the same user account that was used to create the encoded file.
 
'@
 
    if ($help){
        write-host $HelpInfo
        return
        }
    $Credential = (Get-Credential $credential)
    # Look at the object type of the $Credential parameter to determine how to handle it
    switch ( $Credential.GetType().Name ) {
        # It is a credential, so continue
        PSCredential { continue }
        # It is a string, so use that as the username and prompt for the password
        String { $Credential = Get-Credential -credential $Credential }
        # In all other caess, throw an error and exit
        default { Throw "You must specify a credential object to export to disk." }
        }
    # Create temporary object to be serialized to disk
    $export = "" | Select-Object Username, EncryptedPassword
    # Give object a type name which can be identified later
    $export.PSObject.TypeNames.Insert(0,’ExportedPSCredential’)
    $export.Username = $Credential.Username
    # Encrypt SecureString password using Data Protection API
    # Only the current user account can decrypt this cipher
    $export.EncryptedPassword = $Credential.Password | ConvertFrom-SecureString
    # Export using the Export-Clixml cmdlet
    $export | Export-Clixml $Path
    Write-Host -foregroundcolor Green "Credentials saved to: " -noNewLine
    # Return FileInfo object referring to saved credentials
    Get-Item $Path
    }

Export-PSCredential accepts credential information from the user and saves it into an encrypted file. The encrypted file can later be read (use Import-PSCredential) and used as a valid user credential object wherever it might be needed in your PowerShell code. The real beauty of this is that encrypted file can only be properly decrypted by the same user account that created it. This makes it somewhat secure as another user cannot use the credentials (unless they are logged on to your account). I suppose there may be some possible way of hacking the credential, but this is infinitely better than storing in clear text.

Import-PSCredential

?View Code POWERSHELL
function Import-PSCredential {
    param ( $Path = "credentials.enc.xml",
    [switch]$Help)
 
    $HelpInfo = @'
 
    Function : Import-PSCredential
    Date     : 02/24/2011
    Purpose  : Imports user credentials from an encoded XML file.
    Usage    : $cred = Import-PSCredential [-Path ][-Help]
               where
                  $cred       will contain a PSCredential object upon successful completion
                  -Path       specify the file from which credentials will be read
                              if omitted, the file will be "credentials.enc.xml" in the current
                              working directory.
                  -Help       displays this help information
    Note     : Credentials can only be decoded by the same user account that was used to
               create the encoded XML file
 
'@
 
    if ($help){
        write-host $HelpInfo
        return
        }
 
    # Import credential file
    $import = Import-Clixml $Path
    # Test for valid import
    if ( !$import.UserName -or !$import.EncryptedPassword ) {
        Throw "Input is not a valid ExportedPSCredential object, exiting."
        }
    $Username = $import.Username
    # Decrypt the password and store as a SecureString object for safekeeping
    $SecurePass = $import.EncryptedPassword | ConvertTo-SecureString
    # Build the new credential object
    $Credential = New-Object System.Management.Automation.PSCredential $Username, $SecurePass
    Write-Output $Credential
    }

Import-PSCredential can read the exported credential file and return a PSCredential object that you can use anywhere that credentials are accepted in PowerShell.

I absolutely LOVE these two functions as the combination allows me to set up scheduled tasks using PowerShell that can safely use credentials without me exposing any passwords in a script. For day-to-day use, it saves me the trouble of entering credentials for commonly-used scripts that require authentication. I simply modified my scripts to accept user credentials as script parameters.

I have begun to use these two scripts quite extensively, to the point that I now include them in my PowerShell $profile script and give them the short-cut aliases “ecred” and “icred”. To do this, simply add the two functions (above) to your $profile; if you like my aliases, the add the following two lines as well.

?View Code POWERSHELL
new-item -path alias:ecred -value Export-PSCredential |out-null
new-item -path alias:icred -value Import-PSCredential |out-null

Again, kudos to the folks at poshcode.org – all the credit goes to them!

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

   
© 2011 Posh Tips Suffusion theme by Sayontan Sinha

Page optimized by WP Minify WordPress Plugin