This is part of a larger script but, I feel like this part could be streamlined a bit. The code currently works but I feel like doing a Get-Process
call twice is inefficient. Am I wrong?
# Variables:
$ServiceNames = @("HealthTLService","ThreatLockerService")
# Stop & disable some services - if they're running
ForEach ($Service in $ServiceNames) {
Get-Service | Where-Object {($_.Name -eq $Service)} | Stop-Service -Force -ErrorAction SilentlyContinue -Verbose
Get-Service | Where-Object {($_.Name -eq $Service)} | Set-Service -StartupType Disabled -ErrorAction SilentlyContinue -Verbose
}
1 Answer 1
doing a Get-Process call twice is inefficient ?
Well, sure, it's less efficient than doing it once. But there are other considerations. Often we care deeply about whether colleagues can quickly read and understand our code as a prelude to maintaining it. The OP code scores well on that metric, it is very clear.
You might choose to
DRY
it up slightly by defining a function
for the {Get, Where} sequence.
Clearly that wouldn't change the efficiency nor the elapsed time.
Almost equivalently we could follow your suggestion of defining a temp var which is sequentially fed to {Stop, Set}. This cuts lookup time in half.
But my chief concern is that we start out with an
unqualified Get-Service
, which seems to gather
details on every service, follwed by filtering down
to the service of interest.
There is a perfectly good
-Name
option intended to accomplish exactly that.
And accomplish it quickly.
I would much rather do a \$O(1)\$ constant time lookup (or two of them!)
than do even a single \$O(n)\$ operation that is linear
in the amount of stuff installed on the given host.
Some hosts accumulate quite a lot of stuff.
So I would say, do one or two lookups, it hardly matters as long as it happens "fast enough". But tell the tools you're working with about your true goal, rather than asking that they do a lot of busy work which will mostly be later discarded.
-
\$\begingroup\$ It's funny that you mentioned the bit about the ability to read & maintain the script. I often write my code & documentation with full commands just for that reason. Sure, I could have used
?
where I usedWhere-Object
but I want to keep it easy to read for my coworkers who aren't as strong in PS as I am. So, maybe you're right; maybe I leave it alone because I'm not doing the lookup 100 times. \$\endgroup\$RKillcrazy– RKillcrazy2024年06月18日 17:28:13 +00:00Commented Jun 18, 2024 at 17:28