PowerShell Function to Validate Both IPv4 and IPv6 Addresses

Last week, I wrote a blog article about the IP address type accelerator in PowerShell not being 100% accurate and I demonstrated using it for parameter validation. If you want to simply validate an IP Address and return a Boolean, that’s a little more complicated so I decided to write a function to perform that task along with providing detailed information about the IP address when an optional detailed parameter is specified:

The IpAddress parameter can accept one or more IP addresses. By default a Boolean is returned but specifying the detailed parameter returns more information if a valid IP address is specified. IP addresses are also accepted via pipeline input:

testip-5a

The Test-MrIpAddress function shown in this blog article can be downloaded from my PowerShell repository on GitHub.

µ

2 Comments

  1. machinedrummer

    FYI

    This will only work for compressed IPv6 addresses.
    IPv6 typed with leading zeros will be returned as invalid

    $Ip -match [IPAddress]$Ip

    [IPAddress]”fd7f:6c9:f2cc:000f:000f:000f:000f:f1″
    IPAddressToString : fd7f:6c9:f2cc:f:f:f:f:f1

    [IPAddress]”fd7f:6c9:f2cc:0000:0000:0000:0000:f1″
    IPAddressToString : fd7f:6c9:f2cc::f1

    Reply
  2. jedgar

    # Why not use the tryparse method?

    function Test-IP {
    [cmdletbinding()]
    param([string]$ipaddrstring,
    [switch]$detailed)

    $ipaddrobj = [ipaddress]::Any

    # check if address is valid
    if (!([ipaddress]::TryParse($ipaddrstring, [ref]$ipaddrobj)))
    {
    # maybe a port was specified with an ipv4 address?
    # Note that IPv6 with a port (ie [::1]:88) survives the first test above
    if (!([ipaddress]::TryParse($ipaddrstring.split(‘:’)[0], [ref]$ipaddrobj)))
    {
    #nope still invalid
    return $false
    }
    }

    if ($detailed)
    {
    return $ipaddrobj
    }
    else
    {
    return $true
    }

    }

    Reply

Leave a Reply

%d bloggers like this: