Skip to content

Instantly share code, notes, and snippets.

@PrateekKumarSingh
Last active July 3, 2019 00:03
Show Gist options
  • Save PrateekKumarSingh/f3d008a85673f47ce703fe54c2897e4d to your computer and use it in GitHub Desktop.
Save PrateekKumarSingh/f3d008a85673f47ce703fe54c2897e4d to your computer and use it in GitHub Desktop.
Function Get-FolderSize {
param(
$Path = (Get-Location),
$Top = 10,
[Switch] $ShowErrors
)
$Start = Get-Date
$FSO = New-Object -ComObject Scripting.FileSystemObject -ErrorAction Stop
$Folders = Get-ChildItem $Path -Recurse -ea Silentlycontinue -ErrorVariable +err | Where-Object { $_.PSIscontainer } | Select-Object -ExpandProperty fullname
$Objs = Foreach ($Folder in $Folders) {
$FSO.GetFolder($Folder)
}
Write-host "Top $Top Folder sizes" -Foreground Green
$data = $Objs | Select-Object path, size | Sort-Object Size -Descending
$data | Select-Object Path, @{n='FolderSize';e={
$Size = $_.Size
if($Size -ge 1GB){ $SizeWithUnit = "{0:N2} GB" -f ($Size/1gb) }elseif($Size -ge 1Mb){ $SizeWithUnit = "{0:N2} MB" -f ($Size/1mb) }else{$SizeWithUnit = "{0:N2} KB" -f ($Size/1kb)}
$SizeWithUnit
}} -f $Top | Out-Host
if ($ShowErrors) {
if ($err) {
Write-host "Errors Encountered`n" -Foreground Red
$err | foreach{$_.exception}
}
}
$Time = (Get-Date)-$Start
"Total execution time: {0} mins {1} secs" -f $Time.Minutes, $Time.Seconds
}
Get-FolderSize C:\ -Top 5 -ShowErrors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment