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

View all comments

Show parent comments

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/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())

}
}