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
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
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:
When plotted (in Excel), I got the following graph:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With