r/PowerShell • • 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:

https://www.google.com/amp/s/amp.reddit.com/r/PowerShell/comments/2ey9fk/using_ps_to_search_a_huge_file_for_matching_lines/

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:

https://stackoverflow.com/questions/13855788/powershell-fastest-way-to-write-large-body-of-text-to-a-file

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/2011/02/18/speed-up-array-comparisons-in-powershell-with-a-runtime-regex/

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.

2 Upvotes

13 comments sorted by

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 StreamReader and StreamWriter will save you some serious overhead, you also lose abstraction. Get-Content and Set-Content are 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.

$Test = ''
'write-host "lalala"' | Set-Content -path 'Variable:\Test'
$Test
function Test-Function { }
$Test | Set-Content -path 'Function:\Test-Function'
Test-Function

If you need to move from one provider to another, you don't need to update your logic, just the path. if you Implement StreamWriter you 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, StreamWriter is 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 string Große is the same as Grosse. GetHashCode() will show this as different whereas any culture aware comparison will show them as the same.

1

u/[deleted] Jul 05 '17

Culture does matter, but when I am comparing long Unicode strings and doing 100k comparisons, the difference is staggering. From thirty minutes to thirty seconds.

1

u/markekraus Community Blogger Jul 05 '17

Out of curiosity, what is some example code where you are comparing strings with GetHashCode()?

1

u/[deleted] Jul 06 '17 edited Jul 06 '17

Mostly comparing Active Directory attribute values with corresponding attributes in other applications (think HR stuff). Something like this:

# Let's map attributes in AD to attributes for the same users in some other application.

# A hashtable ought to do the trick. Let's scope it in Global because we're lazy and have loops.

$Global:CorrelatedAttributeHashtable = @{

'EMP' = 'EmployeeID' ;
'FIRSTNAME' = 'GivenName' ;
'LASTNAME' = 'sn' ;
'PERSONORG' = 'EmployeeType' ;
'LOCATIONDESCRIPTION' = 'Office' ;
'LOCATIONADDRESS1' = 'StreetAddress' ;
'LOCATIONCITY' = 'l' ;
'LOCATIONSTATE' = 'St'
'LOCATIONZIP' = 'PostalCode'
'JOBDESCRIPTION' = 'Title' ;
'DEPTARTMENTID' = 'DepartmentNumber' ;

}

# For each user in my list.

ForEach($User in $Object.Job.Data.Collated.Keys)
{
    $Global:User = $User

# For each attribute (key, in a key-value pair of the above hashtable)..

ForEach($Key in $Global:CorrelatedAttributeHashtable.Keys)
{

# If I have data in both systems for the user..

    If($Object.Job.Data.Collated.$User.AD -and $Object.Job.Data.Collated.$User.HR)
    {

# If the values of the corresponding attributes for a given user in disparate systems don't match..

        If($Object.Job.Data.Collated.$User.HR.($Key).GetHashCode() -ne $ADA.Job.Data.Collated.$User.AD.$($CorrelatedAttributeHashtable.($Key)).GetHashCode())
        {

 # Tell me.

            Write-Output "For user $User, I don't think these match: [1] $($Object.Job.Data.Collated.$User.HR.($Key))  and [2] $($Object.Job.Data.Collated.$User.AD.$($CorrelatedAttributeHashtable.($Key))) ..."
        }
    }
}

}

1

u/[deleted] Jul 06 '17

FWIW, we do have instances where culture matters, mostly in Named attributes (GivenName,Surname, etc.) but we already normalize the strings before we get to this part.

1

u/markekraus Community Blogger Jul 06 '17

Probably all good in this use-case assuming you don't have culture differences between the 2 systems. We have some instances where some culture squashing occurs in AD because of dependent systems which freak out at characters like ß. This leads to HR system having ß and AD having ss so we couldn't use GetHashCode() if we had to do something like this, at least not on givenName and sn.

1

u/[deleted] Jul 06 '17

Well, you can normalize the string first to account for culture.

function Normalize-String {
[CmdletBinding()]
param(
  [AllowEmptyString()]
  [Parameter(Mandatory = $True, ValueFromPipeline = $True)]
  [string]$Value
)

BEGIN
{
  $OriginalString = [Text.Encoding]::GetEncoding(1252)
}

PROCESS
{
  $UnicodeString = [Text.Encoding]::Convert([Text.Encoding]::Unicode, $OriginalString, [Text.Encoding]::Unicode.GetBytes($Value))
  $UnicodeString = $OriginalString.GetString($UnicodeString)
  $StringBuilder = [Text.StringBuilder]''
  
  ForEach ($Character in $UnicodeString.Normalize([Text.NormalizationForm]::FormD).GetEnumerator())
  {
    If([Globalization.CharUnicodeInfo]::GetUnicodeCategory($Character) -cne [Globalization.UnicodeCategory]::NonSpacingMark)
    {
        $Null = $StringBuilder.Append($Character)
    }
  }

  $(($StringBuilder.ToString()).Trim())

}
}

1

u/[deleted] Jul 06 '17

P.S. Big fan of your posts. :)

3

u/replicaJunction Jul 06 '17

"PowerShell isn't about optimizing computer resources. PowerShell is about optimizing human resources." -J. Snover*

In many cases, the time saved using these external calls and methods is offset by the time taken to research and implement them in a script. PowerShell shines because it's easy to write, once you've wrapped your mind around some of the basic syntax and concepts.

I don't disagree that any of these tips make things faster. I've messed with StreamReader and StreamWriter myself and know firsthand that they're leaps and bounds faster. Where I disagree is that they're easy - for the introductory PowerShell user, .NET calls can be intimidating, especially working with a third-party library like JoeWare.NET. Even experienced developers need to get used to PowerShell's syntax for creating objects and referencing type names.

Your point is certainly valid for high-performance situations, but I wouldn't suggest people turn to these first.

On the other hand, if you believe in them strongly enough, write a module for them! Encapsulate the hard stuff into something that feels like native PowerShell and works similarly to tools people have come to expect. If you remove the barrier of entry, there's no reason not to use the better-performing option.

All of this is just my two cents. At the end of the day, write what PowerShell you will, so long as it gets the job done. :)

*Note: I'm positive I heard him say this because I remember it being so insightful, and I suspect it was in a live Web conference, but for the life of me I can't find the source. If anyone else knows this quote and can point me to a source for it, I'd be very grateful.

0

u/[deleted] Jul 06 '17

In many cases, the time saved using these external calls and methods is offset by the time taken to research and implement them in a script.

Cool. Arbitrary, irrelevant, vacuous, but sure, we'll call it cool.

I don't disagree that any of these tips make things faster.

Cool.

Your point is certainly valid for high-performance situations, but I wouldn't suggest people turn to these first.

Are strawmen on sale at Walmart or something?

On the other hand, if you believe in them strongly enough, write a module for them! Encapsulate the hard stuff into something that feels like native PowerShell and works similarly to tools people have come to expect. If you remove the barrier of entry, there's no reason not to use the better-performing option.

Working on it.

2

u/gangstanthony Jul 05 '17

can you provide reasons for each as well as alternatives and why these proposed are better than those also?

2

u/[deleted] Jul 05 '17 edited Jul 05 '17

They are plainly faster. I know of no other alternatives. I updated the OP with some Google search results.

3

u/dchristian3188 Jul 05 '17

We moved to the .Net methods for reading and writing our config files. The files are small, but we interact with them a lot. Saw a significant speed increase over Get-Content