r/PowerShell • u/[deleted] • Jul 05 '17
Supercharge your PowerShell scripts with these five easy tips.
I am writing this from my phone, so Google is your friend here when looking for examples on how to quickly implement these. If enough folks are drawing a blank I will update this post with examples for each.
1: Replace Get-Content and Import-CSV with .NET's StreamReader.
Examples:
http://www.happysysadm.com/2014/10/reading-large-text-files-with-powershell.html?m=1
2: Replace Out-File and Export-CSV with .NET's StreamWriter.
Examples:
3: Replace Compare-Object with the Match operator using the GetHashCode() method for strings being compared, or for a RegEx generated at runtime.
Examples:
https://blogs.technet.microsoft.com/heyscriptingguy/2015/04/01/use-powershell-to-compare-two-files/
4: Replace Get-AD* with ADFind from JoeWare.NET.
Examples:
http://powershell-guru.com/fastest-powershell-1-count-all-users-active-directory/
5: Replace Set-AD* with ADMod from JoeWare.NET.
EDIT: Yay, downvotes because knowledge is power and power is bad.
5
u/markekraus Community Blogger Jul 05 '17
I'm all for performant code when performance matters. I just prefer the caveat that readability, maintainability, portability, and paradigm alignment are just as important and often trump performance.
While moving to
StreamReaderandStreamWriterwill save you some serious overhead, you also lose abstraction.Get-ContentandSet-Contentare implemented on PSProviders, meaning they are abstracted based on the path. The same code can update a file on a file system, a variable, a function, a SharePoint document library item, a registry item, etc.If you need to move from one provider to another, you don't need to update your logic, just the path. if you Implement
StreamWriteryou have to redo large chunks of logic.But definitely, when you need the performance (such as modifying large numbers of files) and you know for absolute certain that you will be working with a filesystem,
StreamWriteris the bees knees.For array searching... the solution varies greatly depending on your data set size and shape. I'd have to dig through my history, but I've had a bunch of different exchanges about different methods and their performance in different data sets and types. Once you get into the 1000's of items, LINQ really outshines others, but that also depends heavily only strongly typed items. Ultimately, what you are trying to do will also depend on the data set and there is a ton of optimizations that can be done if you know the size and shape of the data... no one solution is better than another in this field... with the exception of where-object which pretty much sucks always performance-wise.
There are some caveats to using
GetHashCode()... like.. if you care about culture.. for example, the stringGroßeis the same asGrosse.GetHashCode()will show this as different whereas any culture aware comparison will show them as the same.