Validate IP Addresses

by Mar 12, 2012

You can use regular expressions and the –match operator to validate user input. Here’s a loop that keeps asking until the user enters a valid IP address:

$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'
  $ok = $ip -match $pattern
  if ($ok -eq $false) {
    Write-Warning ("'{0}' is not an IP address." -f $ip)
    Write-Host -fore Red -back White 'TRY AGAIN!'
  }
} until ( $ok )

Twitter This Tip! ReTweet this Tip!