1

I have some code which is behaving strangely and I am not sure why. I am attempting to validate the user input is a number and that it is less than 255. Pretty easy.

Problem is that numbers from 26 to 99 are not valid for me in my testing. 1-25 are fine, and 100+ seem fine too.. but for some reason 26-99 keep me in the loop.

DO
{
$ip_addr_first = Read-Host 'enter a number less than 255'
} while ($ip_addr_first -notmatch '\p{Nd}+' -or $ip_addr_first -gt 255) 

write-host 'You entered' $ip_addr_first

suggestions welcome on where the problem is, as I'm at a loss here.

1 Answer 1

0

Try

do
{
  $ip_addr_first = Read-Host 'Enter an integer between 0 and 255'
} while ($ip_addr_first -notmatch '^\p{Nd}+$' -or [int] $ip_addr_first -gt 255) 

write-host 'You entered:' $ip_addr_first

Note the [int] cast, which ensures that $ip_addr_first is compared as a number, which makes all the difference here.

Without it, given that $ip_addr_first is a string (the type returned by Read-Host), -gt performs lexical comparison, and 26 is lexically greater than 255, for instance (the same applies to any number (string) starting with 3 or greater).

Also note that I've anchored your regular expression p{Nd}+ with ^ and $ to ensure that the entire input is matched against it (you could make this more permissive by allowing leading and trailing whitespace).


Alternative approach that uses number parsing only:

[int] $ip_addr_first = -1
do
{
  $userInput = Read-Host 'Enter an integer between 0 and 255'
} while (-not ([int]::TryParse($userInput, [ref] $ip_addr_first) -and
               $ip_addr_first -ge 0 -and $ip_addr_first -le 255)) 

write-host 'You entered:' $ip_addr_first
Sign up to request clarification or add additional context in comments.

2 Comments

thanks... the cast is a new one for me since I'm just learning Powershell
@PS_newbie: My pleasure; in PowerShell you often don't have to worry about types, but on occasion you do - generally, it's worth understanding the underlying (.NET) types and how they can be inspected (Get-Member) and converted. My alternative solution shows you how to type-constrain a variable during initialization (a persistent cast, in a manner of speaking).

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.