Techibee.com

Compare secure strings entered through powershell

Can’t we really see the text/password entered through -AsSecureString or with Get-Credential? What I have to do if I got a requirement to compare the passwords? The example scenario for me as a System administrator is, if I have a script which resets admin password acrosss a list of hosts, I will prefer the script to ask for the password two times in secure format and inturn my script should compare these two passwords and proceed only if the passwords entered at two attempts is matched.

In one of the powershell blog author talked about seeing the secure text in plain format. I used that and developed below script for comparing the passwords using powershell.

Write-Host "Hey..!! I am here to compare the password you are entering..."
$pwd1 = Read-Host "Passowrd" -AsSecureString
$pwd2 = Read-Host "Re-enter Passowrd" -AsSecureString
$pwd1_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd1))
$pwd2_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd2))

if ($pwd1_text -ceq $pwd2_text) {
Write-Host "Passwords matched"
} else {
Write-Host "Passwords differ"
}

Let me know if you have any comments/questions…

Exit mobile version