1

I have a PowerShell script that encrypts and stores a password in an XML file - this runs fine. Another script imports that XML and decrypts the password to be passed to another process. This scripts work perfectly fine on one server (server 1) but fails on another (server 2).

Both servers I am running on run are Windows Server 2016 and run PowerShell version 5.1.14393.3053 - yet the script fails on server 2 but not on server 1. I have tried the process using another administrator user but got the same error.

Here is what my scripts look like:

encryptor.ps1 (generates the xml):

$cred = Get-Credential
$cred | Export-CliXml -Path 'D:\cred.xml'

decryptor.ps1 (this is the script that fails):

$credential = Import-CliXml -Path 'D:\cred.xml' 
$PGUser=$credential.UserName 
$PGPwd=$credential.GetNetworkCredential().Password #This causes error shown below

On both servers, running the encryptor.ps1 works fine but running decryptor.ps1 has an issue on server 2.

On server 1, decryptor.ps1 runs fine and I am able to access the variable $PGPwd

On server 2, when decryptor.ps1 is ran I see this error:

Method invocation failed because [Deserialized.System.Management.Automation.PSCredential] does not contain a method named 'GetNetworkCredential'.
At D:\infa_shared\DGDR\RunDump.ps1:3 char:1
+ $PGPwd=$credential.GetNetworkCredential().Password
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (GetNetworkCredential:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
  • 2
    If you look at the type name in the error you'll see that it has `Deserialized` in front of it - since it's been exported and then imported again it's no longer a "live object" so-to-speak. You'll need to manually unprotect the secure string that holds the password: https://stackoverflow.com/questions/7468389/powershell-decode-system-security-securestring-to-readable-password – Mathias R. Jessen Oct 03 '19 at 15:23
  • If you created and exported (encrypted) the credential to an xml file on server1, then you can only decrypt it on server1 and using the same user account you used to create it. To encrypt and decrypt, u need a key, that if u remember, u never supplied. So powershell does something in the background (that i never fully researched) to encrypt the creds using ur account and machine information. If u move the file to another machine, the key is lost on the 2nd machine and hence cannot be decrypted. – Sid Oct 03 '19 at 15:42
  • I am generating a new xml for running on server 2 so it has the necessary machine key to decrypt. Although I just realized that the password I am encrypting contains '&' so this might be causing my issue. I will update if I figure anything out. – Thomas Gallagher Oct 03 '19 at 16:03
  • I dont think the & was the issue because I did the whole process on server 1 and it did not cause the error – Thomas Gallagher Oct 03 '19 at 17:48

0 Answers0