Friday, March 18, 2022

Powershell speed hacks

Powershell can be painfully slow when dealing with larger arrays, reading files and listing large directories. Here are some workarounds.

Arrays
Slow:

$myarray = @()
foreach ($x in $y) {
  $myarray += $x
}

Much faster is working with an arraylist:

$myarray = [System.Collections.ArrayList]@()
foreach ($x in $y) {
  $null = $procarray.Add($x)
}

Reading files
Slow:

get-content $filename

Fast:

([System.IO.File]::ReadAllLines($filename))

Listing large directories
Slow:

$items = get-item "\\server\share\*.csv" | sort LastWriteTime

The fastest workaround i’ve been able to find is actually using a dos prompt. Use dir switches for sorting purposes.
Note: dir returns just text, while get-items returns objects with all sorts of properties. It depends on your use case whether this hack is actually usable or not.

$items = cmd /r dir "\\server\share\*.csv" /OD /B