Skip to content

Instantly share code, notes, and snippets.

@Rapidhands
Created January 16, 2025 10:26
Show Gist options
  • Save Rapidhands/25704e7abc7aefffd6ad444b1fd19484 to your computer and use it in GitHub Desktop.
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
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