Home Contact

The Frog Pond of Technology

Ripples of Knowledge for SharePoint and Other .Net Technologies

News

My blog has moved to WordPress at BrianTJackett.com. Any pages will automatically redirect to the new address in 7 seconds. Please excuse an issues during this migration.

 Subscribe to this blog


About Me

Name:
Brian T. Jackett
Location:
Columbus, OH
Company:
Microsoft

Find me on...

Tag Cloud


Archives

Post Categories

Syndication:

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


Wednesday, January 4, 2012 10:17 AM

Feedback

No comments posted yet.


Post A Comment
Title:
Name:
Email:
Comment:
Verification: