PowerShell Check for Empty SecureString Entry

A few days ago my friend Todd Klindt (click here for his blog, I get helpful advice there all the time) asked the following question on Twitter: ‘Is there a way to see if someone just his enter with “read-host –assecurestring”? I need to test for no input. #powershell’.

SecureString1

Problem

As you may know, secure strings in PowerShell are not readable (unless using ConvertFrom-SecureString or some alternate process).  If attempt to check equality of a secure string against an empty string or the null variable $null you will return a result of false even if the user didn’t enter anything.  How can you check if the secure string is empty then?

 

Solution

What you do have access to is the Length property of the secure string.  Store the input of your secure string into a variable and check it’s length property equals to 0.  If the length is equals to 0 then the user didn’t enter anything.  If it greater than 0 then they did enter something.  See the screenshot example below.

SecureString2

Example:

$myInput = Read-Host -AsSecureString -Prompt "Enter phrase"
if($myInput.Length -eq 0){Write-Host "No input detected"}
else{Write-Host "Input detected"}

Conclusion

This is a very short but not entirely intuitive answer to the question of how to check if a secure string is empty.  At first I thought the length value would be obscured, but since the PowerShell host does visibly show the number of asterisk ‘*’ characters I guess someone else would be able to find out that information easily as well.  I haven’t thoroughly tested this solution but it appears to be working thus far.  Let me know if you find any issues with this approach.

-Frog Out

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s