# Usage: Export-PSCredential [-Credential ] [-Path ] # Export-PSCredential [-Credential ] [-Path ] # If Credential is not specififed, user is prompted by Get-Credential cmdlet. # If a username is specified, then Get-Credential will prompt for password. # If the Path is not specififed, it will default to "./credentials.enc.xml". # Output: FileInfo object referring to saved credentials # # Import-PSCredential [-Path ] # # If not specififed, Path is "./credentials.enc.xml". # Output: PSCredential object function Export-PSCredential { param ( $Credential = (Get-Credential), $Path = "credentials.enc.xml" ) # 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 = New-Object PSObject Add-Member -InputObject $export -Name Username -Value $Credential.Username ` -MemberType NoteProperty # Encrypt SecureString password using Data Protection API $EncryptedPassword = $Credential.Password | ConvertFrom-SecureString Add-Member -InputObject $export -Name EncryptedPassword -Value $EncryptedPassword ` -MemberType NoteProperty # 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 } function Import-PSCredential { param ( $Path = "credentials.enc.xml" ) # 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 }