How to validate the IP address using PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

To validate the IP address using PowerShell, we can use several methods as shown below.

  • Using RegEx method.

  • Using Typecasting method.

Using TypeCasting method.

In this method, we are using System.Net method class IPAddress to validate the IP address.

[ipaddress]$IP = "192.168.0.1"

The above one is valid. Let’s check what $IP stores in.

PS C:\> $IP

Address : 16820416
AddressFamily : InterNetwork
ScopeId :
IsIPv6Multicast : False
IsIPv6LinkLocal : False
IsIPv6SiteLocal : False
IsIPv6Teredo : False
IsIPv4MappedToIPv6 : False
IPAddressToString : 192.168.0.1

The above one is Ipv4 and this method also works for IPv6. See the example below.

PS C:\> [ipaddress]"2001:0db8:85a3:0000:0000:8a2e:0370:7334"

Address :
AddressFamily : InterNetworkV6
ScopeId : 0
IsIPv6Multicast : False
IsIPv6LinkLocal : False
IsIPv6SiteLocal : False
IsIPv6Teredo : False
IsIPv4MappedToIPv6 : False
IPAddressToString : 2001:db8:85a3::8a2e:370:7334

You can notice the difference in AddressFamily property in both the address.

If we enter the wrong range of IP addresses.

PS C:\> [ipaddress]"192.168.0.256"
Cannot convert value "192.168.0.256" to type "System.Net.IPAddress". Error: "An invalid IP address was specified."
At line:1 char:1
+ [ipaddress]"192.168.0.256"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastParseTargetInvocation

It rejects the IP input. You can also use this method in function to validate the IP.

raja
Published on 19-Feb-2021 17:27:07
Advertisements