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:

 1#Requires -Version 2.0
 2function Test-MrIpAddress {
 3
 4<#
 5.SYNOPSIS
 6    Tests one or more IP Addresses to determine if they are valid.
 7
 8.DESCRIPTION
 9    Test-MrIpAddress is an advanced function that tests one or more IP Addresses to determine if
10    they are valid. The detailed parameter can be used to return additional information about the IP.
11
12.PARAMETER IpAddress
13    One or more IP Addresses to test. This parameter is mandatory.
14
15.PARAMETER Detailed
16    Switch parameter to return detailed infomation about the IP Address instead of a boolean.
17
18.EXAMPLE
19     Test-MrIpAddress -IpAddress '192.168.0.1', '192.168.0.256'
20
21.EXAMPLE
22     Test-MrIpAddress -IpAddress '192.168.0.1' -Detailed
23
24.EXAMPLE
25     '::1', '192.168.0.256' | Test-MrIpAddress
26
27.INPUTS
28    String
29
30.OUTPUTS
31    Boolean
32
33.NOTES
34    Author:  Mike F Robbins
35    Website: http://mikefrobbins.com
36    Twitter: @mikefrobbins
37#>
38
39    [CmdletBinding()]
40    param (
41        [Parameter(Mandatory=$true,
42                   ValueFromPipeLine=$true)]
43        [string[]]$IpAddress,
44
45        [switch]$Detailed
46    )
47
48    PROCESS {
49
50        foreach ($Ip in $IpAddress) {
51
52            try {
53                $Results = $Ip -match ($DetailedInfo = [IPAddress]$Ip)
54            }
55            catch {
56                Write-Output $false
57                Continue
58            }
59
60            if (-not($PSBoundParameters.Detailed)){
61                Write-Output $Results
62            }
63            else {
64                Write-Output $DetailedInfo
65            }
66
67        }
68
69    }
70
71}

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:

1Test-MrIpAddress -IpAddress '192.168.0.1', '192.168.0.256'
2Test-MrIpAddress -IpAddress '192.168.0.1' -Detailed
3'::1', '192.168.0.256' | Test-MrIpAddress

testip-5a.png

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

µ