Last active
February 27, 2023 21:48
-
-
Save pipin68k/4355d75d549167d76c06 to your computer and use it in GitHub Desktop.
Get-DirectorySize
This file contains 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 ConvertTo-HumanReadable([long] $size) | |
{ | |
if($size -lt 0) { return "Failed" } | |
if($size -ge 1GB){ | |
"{0,7:#,##0.0}G" -F ($size/1GB) | |
}elseif($size -ge 1MB){ | |
"{0,7:#,##0.0}M" -F ($size/1MB) | |
}elseif($size -ge 1KB){ | |
"{0,7:#,##0.0}K" -F ($size/1KB) | |
}else{ | |
"{0,7:#,##0.0}B" -F $size | |
} | |
} | |
Function Get-DirectorySize([string] $tartgetFolder, [switch]$OrderBySize, [switch]$NonFso, [switch]$AddTotal) | |
{ | |
begin{ | |
$fso = New-Object -ComObject Scripting.FileSystemObject | |
$p = 0 | |
$pmax = (Get-ChildItem $tartgetFolder).Count | |
$order = if($OrderBySize){'SizeByte'}else{'Name'} | |
$sizeTotal, $filesTotal, $foldersTotal = 0, 0, 0 | |
} | |
process{ | |
Get-ChildItem $tartgetFolder| | |
%{ | |
Write-Progress -Activity "Progress" -Status $_ -PercentComplete ($p/$pmax*100) | |
$p += 1 | |
if($_ -is [System.IO.DirectoryInfo]){ | |
if($NonFso){ | |
$byteSize = (Get-ChildItem -Force $_.FullName -Recurse|Measure-Object -Property Length -Sum).Sum | |
}else{ | |
$byteSize = if($fso.GetFolder($_.FullName).size -ge 0){ [long]$fso.GetFolder($_.FullName).size }else{ -1 } | |
} | |
$files = (Get-ChildItem $_.FullName -File -Recurse -Force).Count | |
$folders = (Get-ChildItem $_.FullName -Directory -Recurse -Force).Count | |
}else{ | |
$byteSize = $_.Length | |
$files = 1 | |
$folders = 0 | |
} | |
$sizeTotal += $byteSize | |
$filesTotal += $files | |
$foldersTotal += $folders | |
New-Object PSObject -Property @{ | |
Name = $_.Name | |
SizeByte = $byteSize | |
Size = ConvertTo-HumanReadable $byteSize | |
Files = $files | |
Folders = $folders | |
} | |
}|Sort $order|Format-Table Name,Size,SizeByte,Files,Folders -AutoSize | |
} | |
end{ | |
if($AddTotal){ | |
"Total Size: {0,15}" -f (ConvertTo-HumanReadable $sizeTotal) | |
"Total Size(byte):{0,15}" -f $sizeTotal | |
"Total Files: {0,15}" -f $filesTotal | |
"Total Folders: {0,15}" -f $foldersTotal | |
} | |
} | |
} | |
Export-ModuleMember -Function Get-DirectorySize |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment