Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the user hits enter with no input in a powershell script?

Tags:

powershell

I have a powershell script where I want the user to input a value and the script returns a randomized string for a password. If they just hit enter when prompted for the length of the password, I want it to be a default of 9 characters.

How do I handle no input?

I tried something like this, but don't think it is quite right:

Write-Host Enter the password length requirement:

$length = Read-Host
IF ( $length -eq $NULL) 
    { Do continue on with the value of 9 for the length}
ELSE
    {Use $length for the rest of the script}

The else portion works just fine; however when generating passwords I keep finding myself typing 9 over and over again. I'd rather just hit enter.

Any help is greatly appreciated!

like image 409
John Avatar asked Mar 29 '11 19:03

John


2 Answers

PowerShell is great, because you can shorten code very often and it works :)

if (!$length) { 
  Do continue on with the value of 9 for the length
} ...

Why?

[bool]$null         # False
[bool]''            # False
[bool]'something'   # True
like image 80
stej Avatar answered Oct 08 '22 17:10

stej


I would say "works as designed". Because $lenght is not NULL. the right test is :

if ($length -eq [string]::empty)

So perhaps a conjunction of the two tests.

JP

like image 41
JPBlanc Avatar answered Oct 08 '22 15:10

JPBlanc