8

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!

4 Answers 4

19

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
Sign up to request clarification or add additional context in comments.

3 Comments

In the if block, set $Length to 9 and then you are good to go.
@jason I wanted to show only the condition, I guess John is capable to do the rest :) Anyway, thx for reviewing.
John may not have realized that, I like to be explicit some times. :)
5

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

Comments

2

IF ( $length -eq "")

instead of IF ( $length -eq $NULL)

should do it.

Comments

1

The absolute best way to do this would be to it a parameter to the script and use the V2 validation attributes. This will also prevent them putting in bad data, like strings

param( [Parameter(Mandatory=$true)] [ValidateRange(1,9)] [Int] $Length )

This will give you better validation and consistent and localized errors.

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.