Search This Blog

Sunday, 26 November 2017

PowerShell Tip - Compare Secure Strings

No frills...

So the PC is freshly imaged, but needs connecting to the domain using a script. No available way to authenticate the password before making the method call and fat fingers can screw up the join. For a little extra assurance, enter password twice and compare, but SecureStrings are not comparable, so:

Function Password-DoubleCheck{
  do{
    $pass1=Read-Host -Prompt 'Enter User Password' -AsSecureString
    $pass2=Read-Host -Prompt 'Verfy User Password' -AsSecureString
    $chk1 = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass1))
    $chk2 = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass2))
    if($chk1-ceq$chk2){$validPass=$True}else{$validPass=$False;Write-Host 'Passwords do not match...'}
  }
  until($validPass)
  $pass1
}

Use like:
$password=(Password-DoubleCheck)

Derived from: http://techibee.com/powershell/compare-secure-strings-entered-through-powershell/422

No comments: