Periodically passwords on service accounts need to be updated as all information security best practices recommend. Many shops may not have automated tools that would do this for all their scripts. Many PowerShell scripts may be set to read an encrypted password file. Naturally, this would break after a password update. I needed a quick tool for administrators to quickly update these password files by allowing them to do the input it twice to prevent typos method. So here it is. The file is stored in a text file ending with “.Pw.txt”
# Input and validate password and store encrypted in file for later use. $userId= "myUserID" $pwFile = "$PSScriptRoot\$userId.Pw.txt" do { $password1 = Read-Host "$tryAgain`Enter $adminId Password: " -AsSecureString $password2 = Read-Host "Verify $adminId Password: " -AsSecureString $check1 = ([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password1)).ToString() $check2 = ([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password2)).ToString() if ($check1.SubString(0,($check1.Length)-4) -eq $check2.SubString(0,($check2.Length)-4)) {$pwMatch = $true} else {$tryAgain = "Passwords did not match, try again.`n"; $pwMatch = $false} } Until ($pwMatch) $password1 | ConvertFrom-SecureString | Out-File $pwFile -Force
If you really need to make sure the password was properly encrypted, then you can use this script to recover it back into plain text. Use this sparingly and don’t leave the script lying around to be used. One may choose to use NTFS to lock down read to the password file even further. However, here it is:
# get the iLO password and convert to plain text $userId= "myUserID" $pwFile = "$PSScriptRoot\$userId.Pw.txt" $SecurePassword = Get-Content $pwFile | ConvertTo-SecureString $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword) $UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) $UnsecurePassword
Here’s an example to securely pull the password into a credential pair for use in many commandlets as $creds:
$userId= "myUserID" $pwFile = "$PSScriptRoot\$userId.Pw.txt" $pwd = Get-Content $pwFile | ConvertTo-SecureString $creds = New-Object System.Management.Automation.PSCredential -ArgumentList $userId, $pwd