Use Regular Expression to Validate Input

PowerShell can use regular expressions to validate user input. All you need is a regular expression that adequately defines the pattern you are seeking. Fortunately, you do not need to create regular expressions from scratch. Simply Google them and then replace the pattern string in the example below to validate other user input:

$pattern = '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.)' +
'{3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'

do {
$ip = Read-Host "Enter IP"
} while ($ip -notmatch $pattern)

Twitter This Tip! ReTweet this Tip!


Posted Nov 17 2009, 08:00 AM by ps1
Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.