Validate an IP address in PowerShell

Today I needed to validate an IP address after a user types it in to a script.  I don’t want to ping or check connectivity, I just want to validate that the format looks like a valid IP address.  I looked at various regex expressions which were getting complicated.  Then I stumbled upon this little nugget:

This little PowerShell snippet uses a .NET method to validate that our address is in a valid format.

IF ([BOOL]($newIP -as [IPADDRESS])){
  Write-Host "is a valid address" 
} else {
  write-Host -ForegroundColor Red "is an invalid address"

Though do note that it only validates the format.


Posted on August 17, 2012 at 19:57 by simon · Permalink
In: Power Shell · Tagged with: , ,

One Response

Subscribe to comments via RSS

  1. Written by Brent
    on 18 January 2017 at 13:20
    Reply · Permalink

    This has the same issue as other IP validates have, they don’t work correctly. Yes your script works, but if you only put in 3 octets of the IP it says its valid, huh?

Subscribe to comments via RSS

Leave a Reply