I have this code in PowerShell and it does not work! any help?
I just need it to make sure that the string is a working IP not 999.999.999.999 or a normal string
just an IP [0....255].[0....255].[0....255].[0....255]
if ($newIP -match "(\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b)") { $x = $True}
cheers
Type cast to [System.PowerShell Type accelerator [IPAddress] which is also an alias of System. Net. IPAddress class can validate IP Addresses if it is typecast-ed against it, and will throw an error when IP Address is out of range or is incorrect in format.
One of the most useful and popular PowerShell regex operators is the match and notmatch operators. These operators allow you to test whether or not a string contains a specific regex pattern. If the string does match the pattern, the match operator will return a True value.
We can use InetAddressValidator class that provides the following validation methods to validate an IPv4 or IPv6 address. isValid(inetAddress) : Returns true if the specified string is a valid IPv4 or IPv6 address. isValidInet4Address(inet4Address) : Returns true if the specified string is a valid IPv4 address.
Here is a more compact one:
\b(([01]?\d?\d|2[0-4]\d|25[0-5])\.){3}([01]?\d?\d|2[0-4]\d|25[0-5])\b
How about:
[bool]($newIP -as [ipaddress])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With