Created
January 16, 2025 10:26
-
-
Save Rapidhands/25704e7abc7aefffd6ad444b1fd19484 to your computer and use it in GitHub Desktop.
Compare COM method and Powershell method (using Get-ChildItem) to get the size of a folder. COM method is incredibly faster
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Compare-FolderSizeMethods | |
{ | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory)] | |
[string]$Path | |
) | |
$results = @{ | |
COM = 0 | |
PowerShell = 0 | |
} | |
# Test COM method | |
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew() | |
try | |
{ | |
$fso = New-Object -ComObject Scripting.FileSystemObject | |
$folder = $fso.GetFolder($Path) | |
$size = $folder.Size | |
} | |
finally | |
{ | |
if ($fso) | |
{ | |
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($fso) | Out-Null | |
} | |
} | |
$stopwatch.Stop() | |
$results.COM = $stopwatch.ElapsedMilliseconds | |
# Test PowerShell method | |
$stopwatch.Restart() | |
$size = (Get-ChildItem -Path $Path -Recurse -Force -ErrorAction SilentlyContinue | | |
Measure-Object -Property Length -Sum).Sum | |
$stopwatch.Stop() | |
$results.PowerShell = $stopwatch.ElapsedMilliseconds | |
[PSCustomObject]@{ | |
Path = $Path | |
'COM_Time_ms' = $results.COM | |
'PS_Time_ms' = $results.PowerShell | |
'Difference_ms' = $results.PowerShell - $results.COM | |
'COM_Faster_By_Factor' = [math]::Round($results.PowerShell / $results.COM, 2) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment