How to tell if a number is within a range in PowerShell

If the server name is really just a number then:

$num = [int]$serverName
if ($num -ge 500 -and $num -le 549) {
    ... do one thing
}
else  {
    ... do another
}

As a reply to both answers; code clarity and performance both matter, so I did some testing. As with all benchmarking, your results may differ; I just did this as a quick test..

Solution 1

(($value -ge $lower) -and ($value -le $upper))

Solution 2

$value -In $lower .. $upper

Test

$value = 200
$lower = 1

for ($upper = $lower; $upper -le 10000000; $upper += $upper) {
    $a = Measure-Command { (($value -ge $lower) -and ($value -le $upper)) } | Select -ExpandProperty Ticks
    $b = Measure-Command { ($value -in $lower .. $upper) } | Select -ExpandProperty Ticks
    "$value; $lower; $upper; $a; $b"
}

Results:

Enter image description here

When plotted (in Excel), I got the following graph:

Enter image description here

Conclusion

For small ranges, there is no big difference between solutions. However, since the performance penalty for larger ranges does occur (measurable starting at 256 elements), and you may not have influence on the size of the range, and ranges may vary per environment, I would recommend using solution 1. This also counts (especially) when you don't control the size of the range.


Use the -In operator and define a range with ..

$a = 200
$a -In 100..300

As a bonus: This works too. Here, PowerShell silently converts a string to an integer

$a = "200"
$a -In 100..300

Output for both examples is

True

Tags:

Powershell