Validate IP Addresses

Share |

Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Powershell Plus

13 Free SQL Tools from Idera

Free Ebook: Mastering Powershell


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!

Posted Mar 12 2012, 06:00 AM by ps1


Matt_Anderson wrote re: Validate IP Addresses
on 03-12-2012 4:40 PM

Alternatively you could use exceptions from the byte array constructor and/or System.Net.IPAddress constructor:

PS C:\> [byte[]] $ip = "".Split(".")

PS C:\> [byte[]] $ip2 = "8.8.8".Split(".")

PS C:\> [byte[]] $ip3 = "".Split(".")

Cannot convert value "256" to type "System.Byte". Error: "Value was either too large or too small for an unsigned byte."

At line:1 char:14

+ [byte[]] $ip3 <<<<  = "".Split(".")

   + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException

   + FullyQualifiedErrorId : RuntimeException

PS C:\> [System.Net.IPAddress] $ip

Address           : 134744072

AddressFamily     : InterNetwork

ScopeId           :

IsIPv6Multicast   : False

IsIPv6LinkLocal   : False

IsIPv6SiteLocal   : False

IPAddressToString :

PS C:\> [System.Net.IPAddress] $ip2

Cannot convert value "System.Byte[]" to type "System.Net.IPAddress". Error: "An invalid IP address was specified.

Parameter name: address"

At line:1 char:28

+ [System.Net.IPAddress] $ip2 <<<<

   + CategoryInfo          : NotSpecified: (:) [], RuntimeException

   + FullyQualifiedErrorId : RuntimeException

Irwin Strachan wrote re: Validate IP Addresses
on 03-13-2012 3:51 AM

I'm having trouble deciphering the pattern. How do you go about it?

Copyright 2012 All rights reserved.