Validate User Input

by Dec 8, 2008

When you ask users for input you never know what they enter so it is a good idea to validate user input before using it. A great and easy way to do this is using a Do loop together with the -like operator. The following code validates user input to make sure a Web address was entered:

Do {
$input = Read-Host 'Homepage'
} While ($input -notlike 'www.*.*')

You can easily expand this template. The next example asks for an e-mail address and outputs a warning if the user did not enter one:

$warning = 'Enter Email Address! >'
Do {
Write-Host -ForeGround 'Yellow' -back 'black' -noNewLine $warning
$email = Read-Host
$warning = 'You did not enter a valid email address. Please try again! >'
} While ($email -notlike '*@*.*')

Of course, pattern matching with -like and -notlike is very basic. If you need to match more complex patterns, you should use -match and Regular Expressions.