Home > database >  powershell how to pass multiple number into number range in if condition
powershell how to pass multiple number into number range in if condition

Time:10-29

I have below code, I am passing 101,102 number in $a:

$a = Read-host enter number 
$a -In 100..300

It's gives me 'False' instead 'True' ,I want use this concept in my script but unable to get true result Reference link: How to tell if a number is within a range in PowerShell

CodePudding user response:

If you're planning to pass multiple numbers separated by a comma, first you'll need to convert the string into an array and, in addition, you will need to loop through those values and compare each of them with the -in operator.

Here is an example of how to achieve that:

[regex]::Matches(
    (Read-host "Enter numbers separated by a comma"), '\d '
).Value.ForEach({$_ -in 100..300})

Example:

Enter numbers separated by a comma: 123,5000,10,200
True
False
False
True

CodePudding user response:

If you are entering 101,102 verbatim when prompted, then it's being interpreted as a string, not an integer and cannot be cast as anything else automatically. The string 101,102 is not an integer in the range of 100 to 300.

If you enter 101 or 102 when prompted, True will be returned.

CodePudding user response:

There's good information in the existing answers, but let me attempt a systematic explanation:

  • Read-Host only ever returns a single object, of type string ([string]).

  • If you want to interpret that string as a list of items, you'll have to do your own splitting, such as with -split, the string splitting operator.

  • Additionally, if you want the string (tokens) to be numbers, you'll have to cast to the desired numeric type, e.g. [int]

  • Finally, the -in operator can only test a single LHS object against the RHS array. To test multiple ones you need to test each, which the sample code below does with the .Where() array method:

# Prompt the user for a comma-separated list of numbers, split the result
# string into individual number strings and convert them to integers.
# Note: This will fail with non-numeric tokens.
#       Entering nothing will yield a single-element array containing 0
#       Add error handling as needed.
$numbers = [int[]] ((Read-Host 'Enter list of numbers') -split ',')

# Make sure all numbers provided are in the expected range.
if ($outOfRangeNumbers = $numbers.Where({ $_ -notin 100..300 })) {
  Write-Warning "Numbers that are out of range: $outOfRangeNumbers"
}
  • Related