CPU usage of 3-4% isn't that much. That being said, use Measure-Command
to see which statements consume time and which are not.
In the general sense, try and avoid unecessary work. That is, some commandlets provide built-in filtering. For such, piping output to ?
is wasteful. Consider Get-Process
:
Measure-Command -Expression { get-process | ? { $_.processname -eq "iexplore" } }
Measure-Command -Expression { get-process -name "iexplore" }
In my system the first one takes about 13 ms on the average. The second one takes about 1.5 ms. The improvement is about a decade.
In addition, consider storing command results into variables instead of re-running the commands all the time. For example, the code is littered with statements like ipconfig | Select-String
. Instead of those, store the output into a variable and update the variable only when necessary.
manpreet
Best Answer
2 years ago
I.ve come at this many different ways and looked on alot of sites about Efficient Powershell Scripts but I still could use help making this script more efficient...It uses 3-4% of CPU. The Main Drag on the processor is the MainLogic function. It is nested in a While($true) loop at the start of the body of my script and runs all the time...when certain parameters in the MainLogic function change the function breaks and certain if then statements are tested in the body of the script. I'm trying to learn how to write more efficient code ...Im practicing to be a Lisp Developer and I think a good lesson on Powershell efficiency would be good for us all . I've rewritten this script 3 times and I still need help making it better...I see most windows process use almost no CPU and they run all the time and are very smart code. I'd love to be that good. I need everything in the script\I have to test all he things tested in the script. I commented it alot to aid in someone helping me
Ive tried these things:
Is this just a big script or am I not seeing the big picture as far as coding....pls cite online resource to help me write more efficient code, If you see Holes in my Logic.
Here is my script: the MainLogic Function is the Processor hog and all that needs to be looked at....I added the rest to aid in my assistance. Thanks in Advance