Validate Read-Host Input

by Jan 22, 2016

Beginning in PowerShell 4.0, you can use validators for variable assignments. This gives you a quick and easy way of validating user input, too. The next line accepts only user input that matches the regular expression in the validator. It only accepts input in the format "server" plus at least one and at most four digits:

[ValidatePattern('^server\d{1,4}$')]$Server = Read-Host "Enter a servername (serverXXXX)" 

When the user enters invalid input, an exception is raised. You could catch the exception and handle it like this:

do
{
    try {
    [ValidatePattern('^server\d{1,4}$')]$Server = Read-Host "Enter a servername (serverXXXX)" 
    } catch {}
} until ($?)

This would repeat Read-Host until there was no error anymore.

 

Throughout this month, we'd like to point you to three awesome community-driven global PowerShell events taking place this year:

Europe: April 20-22: 3-day PowerShell Conference EU in Hannover, Germany, with more than 30+ speakers including Jeffrey Snover and Bruce Payette, and 60+ sessions: www.psconf.eu.

Asia: October 21-22: 2-day PowerShell Conference Asia in Singapore. Watch latest announcements at www.psconf.asia

North America: April 4-6: 3-day PowerShell and DevOps Global Summit in Bellevue, WA, USA with 20+ speakers including many PowerShell Team members: https://eventloom.com/event/home/PSNA16

All events have limited seats available so you may want to register early.

Twitter This Tip! ReTweet this Tip!