PowerShell Tip: Validating IP Address as a Parameter
I find myself many times writing an Advanced Function that takes as its parameters only IP Addresses. A quick way I found for validating that an IP Address was passed is using the [IPAddress] Type Accelerator and the parameter option of [ValidateScript()] if we look at the type accelerator it self if we pass a valid IPv4 or IPv6 Address we get an IPAddress object:
PS C:\Windows\system32> [ipaddress]"192.168.1.1" Address : 16885952 AddressFamily : InterNetwork ScopeId : IsIPv6Multicast : False IsIPv6LinkLocal : False IsIPv6SiteLocal : False IsIPv6Teredo : False IsIPv4MappedToIPv6 : False IPAddressToString : 192.168.1.1
Lets try passing a none valid IPv4 Address:
PS C:\Windows\system32> [ipaddress]"260.0.0.1" Cannot convert value "260.0.0.1" to type "System.Net.IPAddress". Error: "An invalid IP address was specified." At line:1 char:1 + [ipaddress]"260.0.0.1" + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [], RuntimeException + FullyQualifiedErrorId : InvalidCastParseTargetInvocation
As we can see it generated an error that says that the value provided is an invalid IP address.
Here is an example function where we can see how we would set the paramter:
function Test-IPaddress { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateScript({$_ -match [IPAddress]$_ })] [string] $IPAddress ) Begin { } Process { [ipaddress]$IPAddress } End { } }
And this is how it would look when used:
PS C:\Windows\system32> Test-IPaddress -IPAddress "192.168.1.1" Address : 16885952 AddressFamily : InterNetwork ScopeId : IsIPv6Multicast : False IsIPv6LinkLocal : False IsIPv6SiteLocal : False IsIPv6Teredo : False IsIPv4MappedToIPv6 : False IPAddressToString : 192.168.1.1 PS C:\Windows\system32> Test-IPaddress -IPAddress "260.0.0.1" Test-IPaddress : Cannot validate argument on parameter 'IPAddress'. Cannot convert value "260.0.0.1" to type "System.Net.IPAddress". Error: "An invalid IP address was specified." At line:1 char:27 + Test-IPaddress -IPAddress "260.0.0.1" + ~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Test-IPaddress], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Test-IPaddress