search
Categories
Sponsors
VirtualMetric Hyper-V Monitoring, Hyper-V Reporting
Archive
Blogroll

Badges
MCSE
Community

Cozumpark Bilisim Portali
Validating IP Address in PowerShell
Posted in Windows Powershell | No Comment | 2,011 views | 15/07/2015 12:53

There are many ways to validate an ip address in PowerShell. Common method is usually regex. But if you want to validate both IPv4 and IPv6 ip address in same Regex query, then life could be difficult. For example this is an query example for ipv4 and ipv6 validator regex:

'/^(?>(?>([a-f0-9]{1,4})(?>:(?1)){7}|(?!(?:.*[a-f0-9](?>:|$)){8,})((?1)(?>:(?1)){0,6})?::(?2)?)|(?>(?>(?1)(?>:(?1)){5}:|(?!(?:.*[a-f0-9]:){6,})(?3)?::(?>((?1)(?>:(?1)){0,4}):)?)?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?4)){3}))$/iD'

Personally I don’t want to deal with this kind of Regex queries. It’s hard to read, easy to make mistake. So let’s try another simple way, using [ipaddress] type.

1
2
3
4
5
6
7
8
9
10
11
PS C:\Users\Yusuf> [ipaddress]"10.10.10.0"
 
Address            : 657930
AddressFamily      : InterNetwork
ScopeId            :
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 10.10.10.0

As you see, it validates ipv4 address. So what about ipv6?

1
2
3
4
5
6
7
8
9
10
11
12
PS C:\Users\Yusuf> [ipaddress]"::1"
 
 
Address            :
AddressFamily      : InterNetworkV6
ScopeId            : 0
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : ::1

Yes, it pretty works with ipv6 address. So what happens if I use a string?

1
2
3
4
5
6
7
PS C:\Users\Yusuf> [ipaddress]"::a333SSSSS"
Cannot convert value "::a333SSSSS" to type "System.Net.IPAddress". Error: "An invalid IP address was specified."
At line:1 char:1
+ [ipaddress]"::a333SSSSS"
+ ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastParseTargetInvocation

So we can simply use something like this for validation:

1
2
3
4
if ("10.10.10.0" -as [ipaddress])
{
   write-output Validated!
}

Now you can use your expression between if blocks.



Leave a Reply