8

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

1
  • 2
    you can find a ton of matches for IP address by googling or directly here at stackoverflow. See here for the formal matching (called also complex beast :) Commented May 5, 2011 at 17:45

5 Answers 5

29

How about:

[bool]($newIP -as [ipaddress])
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work all the time. If you put in "10.10" for example, it will say it's a valid IPAddress because the it will convert it to "10.0.0.10". See stackoverflow.com/questions/39988644/… for more info
1

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

1 Comment

For those stumbling onto this thread now 11 years later: this solution is not correct as the expression will evaluate 0.0.0.0 as a valid IP address which it is not. The problem is the \d which allows zeros.
0

or even shorter

^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$

2 Comments

I wanted to add that I have been using this IPRegex and have tested it against hundreds of IP addresses. It works like a charm.
What? That's basically saying it accepts any combination of 1 to 3 digits and has a period between them...
0

This works fine and errors if not full IP

$Name = "1.1" ; [bool]($Name -as [ipaddress] -and ($Name.ToCharArray() | ?{$_ -eq "."}).count -eq 3) 

2 Comments

Welcome to StackOverflow Colin. However, if this is an answer to the question (I am not sure) then it requires a little rephrasing of the explanation for clarity and readability and maybe a little formatting of the shown code.
Please take the tour at your convenience.
-2

The following will not work ^(?:[0-9]{1,3}.){3}[0-9]{1,3}$ Take for example the part that needs to match the last octet from the IP Address [0-9]{1,3} - This will not match only number in the interval 0 to 255 Your best approach will be to dived checking of a single octet to 250 to 255; 240 to 249; 100 to 199; 10 to 99; and 0 to 99.

1 Comment

There is no word in main question that ^(?:[0-9]{1,3}.){3}[0-9]{1,3}$ should work. Instead of writing what will not work please try to write what will with some proper examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.