0

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?

Randy Orrison
  • 1,259
  • 2
  • 15
  • 14

2 Answers2

1

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

Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
1

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"
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206