Get-ChildItem Performance

I was writing some PowerShell scripts to scan disks for certain types of malware and realized that Get-ChildItem was kind of slow. I googled around and found this site which demonstrated using robocopy.exe and dir as faster alternatives to Get-ChildItem.

Here were the results I had searching for LNK files on my disk using both methods. First, I checked that Get-ChildItem and robocopy.exe produced the same results.

Get-ChildItem produced 442 results and took 17 seconds:

PS C:\> (Get-ChildItem -Path C:\ -Recurse -Force -ErrorAction SilentlyContinue -Filter "*.lnk" |select FullName).Length
442
PS C:\>
PS C:\> (Get-History)[-1].EndExecutionTime - (Get-History)[-1].StartExecutionTime


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 17
Milliseconds      : 98
Ticks             : 170988716
TotalDays         : 0.000197903606481481
TotalHours        : 0.00474968655555556
TotalMinutes      : 0.284981193333333
TotalSeconds      : 17.0988716
TotalMilliseconds : 17098.8716

robocopy.exe produced 443 results and took 10 seconds. The extra result ended up being a blank line in robocopy’s output. This can be trimmed by piping robocopy’s output through findstr /r /v '^$'

PS C:\> (robocopy C:\ NULL *.lnk /S /L /NJH /NJS  /FP /NC /NDL  /R:0 /W:0 /ns).Length
443
PS C:\> (Get-History)[-1].EndExecutionTime - (Get-History)[-1].StartExecutionTime


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 10
Milliseconds      : 150
Ticks             : 101501906
TotalDays         : 0.00011747905787037
TotalHours        : 0.00281949738888889
TotalMinutes      : 0.169169843333333
TotalSeconds      : 10.1501906
TotalMilliseconds : 10150.1906

dir, which is built into cmd.exe, was roughly as fast as robocopy.exe when I tried, also taking 10 seconds and producing 442 results:

PS C:\> (cmd /c "dir C:\*.lnk /a-d /-c /s /b").Length
442
PS C:\> (Get-History)[-1].EndExecutionTime - (Get-History)[-1].StartExecutionTime


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 10
Milliseconds      : 323
Ticks             : 103231416
TotalDays         : 0.000119480805555556
TotalHours        : 0.00286753933333333
TotalMinutes      : 0.17205236
TotalSeconds      : 10.3231416
TotalMilliseconds : 10323.1416

I ran these tests a few more times and got consistent results. Get-ChildItem always took several more seconds than robocopy.exe or dir. robocopy.exe and dir always finished within a second of each other.

This is good to know when writing scripts that scan large directories or the entire filesystem. Using dir or robocopy can likely offer a tremendous speed boost to these types of scripts.

Leave a comment