Five quick tips to improve performance of powershell scripts. Don't take my word for them either, each tip links to an article written by people smarter than I am!
Don't use the += operator!
It's not appending to your array... It makes a copy of the original array adding the new data then deletes the old array. This won't scale well at all. Dave Wyatt has come up with a great solution.
http://powershell.org/wp/2013/09/16/powershell-performance-the-operator-and-when-to-avoid-it/
Foreach-object can be more efficient than Foreach
When you use a foreach the entire collection of objects is loaded into memory first. foreach-object processes them one at a time. There's an interesting explanation here from Ketan Thakkar
http://social.technet.microsoft.com/Forums/en-US/e8da8249-ea91-4772-ae85-582a4b37425b/powershell-foreachobject-vs-foreach
Filter on the "Left Side" of the Pipe
If you are using the pipeline see if you can filter before piping to the where-object commandlet. Most commonly for me in get-wimobject or get-aduser. If you use a -filter well you won't have to bring the entire dataset down to be filtered on your client. Martin Pugh has done some interesting analysis on this kind of thing here
http://thesurlyadmin.com/2012/10/08/powershell-and-string-searches/
Use Multiple Threads where you can
Can the job be run in Multiple threads? If so it'll be worth the effort to get your head around the complexities of Multithreading. Powershell has the concept of jobs. Here's a pretty good example;
http://stackoverflow.com/questions/16360019/how-do-i-add-multi-threading
Measuring performance of your Scripts
So how do we prove these tips will actually improve performance? Well we can use measure-command! It'll time how long it takes for a particular command to execute. So we can use this to benchmark and work on optimizing our scripts performance. Documentation is here;
http://technet.microsoft.com/en-us/library/ee176899.aspx
Performance is completely depending upon good input and level of dedication. In most of the occasion we have found that programmer and professionals are giving their best performance while increasing their percentage of dedication level.
ReplyDeleteThanks for sharing this. I am not too good with these things so I have been researching online for a good performance monitoring software to monitor everything for my small business. I have to find what's easiest for me.
ReplyDelete