How do I check if a password in a System.Security.SecureString is empty?

246 Views Asked by At

I'm prompting in a script for the user to enter a password for a new account. I know that using the -AsSecureString parameter causes it to return a System.Security.SecureString object.

$AccountPassword = Read-Host -AsSecureString -Prompt "Password"

I just want to check that the password they've entered isn't blank. If I just hit enter at the Password prompt, the tests that I've tried on the $AccountPassword variable are not detecting that it's empty:

if (!$AccountPassword) {
  throw "Password must not be empty"
}

if ($AccountPassword = "") {
    throw "Password must not be empty"
}

Is there a way to check the System.Security.SecureString variable directly, or do I need to convert it to plain text in order to test it?

2

There are 2 best solutions below

0
On BEST ANSWER

You can use Length property of System.Security.SecureString class which will return the number of characters in the current secure string

0
On

Just like a regular [string], [securestring] instances have a Length property reflecting the length of the wrapped string value:

if ($AccountPassword.Length -eq 0) {
  throw "Password must not be empty"
}