Skip to content

Instantly share code, notes, and snippets.

@XPlantefeve
Last active February 14, 2019 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save XPlantefeve/10daa4b84cda73df19290b4a73709766 to your computer and use it in GitHub Desktop.
Save XPlantefeve/10daa4b84cda73df19290b4a73709766 to your computer and use it in GitHub Desktop.

Two versions of Get-FolderSize, to get the size of a folder and its content.

One version is a pure Powershell one. The other uses Robocopy to do its job. The Robocopy version is usually quicker. The bigger the folder, the most impressive the difference (Sometimes though, the first access is slower, and I don't understand why).

Of note: Robocopy has been written as optimised for speed, whereas Powershell builds a .NET object for every file, hence the big difference in speed. Another plus of the Robocopy version is that it never breaks on long filepaths.

function Get-FolderSizeRC($Path) {
if ( robocopy $Path c:\dummy /e /r:0 /w:0 /b /BYTES /nfl /ndl /np /njh /l | ? { $_ -match 'Bytes :\s*(?<size>\S+)' } ) { return [int64]$Matches.size }
}
function Get-FolderSizePS($Path) {
return ( ls -Recurse -Path $Path -Force | measure -Property length -Sum ) | select -ExpandProperty Sum
}
function test($Path) {
Write-Host -Object "Testing $Path" -ForegroundColor Cyan
"Read folder size (RC): $([math]::Round((Measure-Command { $size = Get-FolderSizeRC -Path $Path } | select -ExpandProperty TotalSeconds),1))s / $size ($([math]::Round(($size/1Mb)))Mb)"
"Read folder size (PS): $([math]::Round((Measure-Command { $size = Get-FolderSizePS -Path $Path } | select -ExpandProperty TotalSeconds),1))s / $size ($([math]::Round(($size/1Mb)))Mb)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment