3

#PSTip Prompt until satisfied

Sometimes you need to prompt a user for input so you can base your script upon it. The Read-Host cmdlet is made just for that.

PS> $result = Read-Host 'Enter a number between 1 and 5'
Enter a number between 1 and 5: 3

PS> $result
3

What if the user entered something you didn’t expect? Your script fails to execute it. For example, the user supplied a higher or a lower  number or even a non-digit character.

With the following loop, a do-while loop, you can force the user to enter a valid number. A prompt will appear as long as the result doesn’t meet your criteria.

do{
    $result = Read-Host 'Enter a number between 1 and 5'
}
while(1..5 -notcontains $result)

Enter a number between 1 and 5: 0
Enter a number between 1 and 5: 6
Enter a number between 1 and 5: a
Enter a number between 1 and 5: 3

PS> $result
3

As you can see all three attempts to assign a non valid value resulted in a re-prompt. It will continue to execute until the user enters a value your script is expecting to work with.

Filed in: Columns, Tips and Tricks Tags: , , ,

3 Responses to "#PSTip Prompt until satisfied"

  1. Tim Bolton says:

    Very cool! I used something similar for the input of our 10 digit phone numbers –

    # The New Phone Number & Extension & First Six of number for the User

    Do {

    $Phone=Read-Host “What is the New 10 digit Phone Number with dashs? ”

    } while ($Phone -match “^ddd-ddd-dddd$” -ne “True” )

    $Extension=$Phone.substring($phone.length-4)

    $FirstSix = $Phone.Substring(0,7)

  2. Super Cool and so very handy ! 🙂

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: