I'm trying to update a local admin account password. I don't want to pass the password in plain text, so i found a workflow (https://www.pdq.com/blog/secure-password-with-powershell-encrypting-credentials-part-2/) that will allow me to encrypt PW's.
#Change password for TestAccount
$User = 'TestAccount'
$PasswordFile = "$PsScriptRoot\Password.txt"
$KeyFile = "$PsScriptRoot\AES.key"
$key = Get-Content $KeyFile
$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential ` -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $key)
$adsiUser = [adsi]"WinNT://localhost/$User,user"
$adsiUser.SetPassword($MyCredential.Password)
I received the error
Exception calling "SetPassword" with "1" argument(s): "Type mismatch.
(Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
So my google-fu allowed me to decrypt the password with
$decodedpassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($MyCredential.Password))
But now there's a trail of cookies in my script... is there any way to pass this as a Secure String?
Thanks, Paul
Use the Built-in method GetNetworkCredential()
to get the plain text password from the Credential Object
So Change this line:
$adsiUser.SetPassword($MyCredential.Password)
To This:
$adsiUser.SetPassword($MyCredential.GetNetworkCredential().Password)
For short Credential Save/Load Tutorial:
#To Save Credential to file
$pass = "123456" | ConvertTo-SecureString -AsPlainText -Force
$pass | ConvertFrom-SecureString | Set-Content c:\temp\pass.txt
#To Load Credential From Text
$username = "userName"
$encrypted = Get-Content c:\temp\pass.txt | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PsCredential($username, $encrypted)
#To Show the Plain text Password from the Credential Object
$credential.GetNetworkCredential().Password
User contributions licensed under CC BY-SA 3.0