Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

I need a way to start services on a server if the hostname value is between 500-549.

If it is not in that range then other services will be started.

I know how to do it all except identify if the number is a value between 500-549 so servernames containing values up to 499 and from 550-999 will have other services started.

So for example, the desired result would be:

server 500 start service A
server 530 start service b
server 660 start service A
like image 627
brittonv Avatar asked Apr 30 '14 22:04

brittonv


3 Answers

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
like image 103
nixda Avatar answered Oct 19 '22 00:10

nixda


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
}
like image 27
Keith Hill Avatar answered Oct 19 '22 00:10

Keith Hill


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.

like image 20
oɔɯǝɹ Avatar answered Oct 18 '22 23:10

oɔɯǝɹ