Skip to content

Instantly share code, notes, and snippets.

@santisq
Last active September 11, 2023 02:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santisq/27c17417fa5d5e8f50b6f419e6ffe6fa to your computer and use it in GitHub Desktop.
Save santisq/27c17417fa5d5e8f50b6f419e6ffe6fa to your computer and use it in GitHub Desktop.
gets file count and total (recursive) size of every folder
# This is not really good... if you want the real deal, check out:
# https://github.com/santisq/PSTree
function Get-DirectoryInfo {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ValueFromPipeline)]
[alias('FullName')]
[ValidateScript({
if(Test-Path $_ -PathType Container) {
return $true
}
throw 'Directories only!'
})]
[string[]] $LiteralPath,
[Parameter()]
[switch] $Force
)
begin {
class Tree {
[string] $FullName
[Int64] $Count
[Int64] $Size
[string] $FriendlySize
[void] AddSize([Int64] $Size) {
$this.Size += $Size
}
[void] SetFriendlySize() {
# Inspired from https://stackoverflow.com/a/40887001/15339544
$suffix = "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
$index = 0
$length = $this.Size
while ($Length -ge 1kb) {
$Length /= 1kb
$index++
}
$this.FriendlySize = [string]::Format(
'{0} {1}',
[math]::Round($Length, 2), $suffix[$index]
)
}
}
$indexer = [ordered]@{}
$stack = [Collections.Generic.Stack[IO.DirectoryInfo]]::new()
$PSBoundParameters['Directory'] = $true
}
process {
foreach($folder in $LiteralPath | Get-Item) {
$stack.Push($folder)
}
while($stack.Count) {
$PSBoundParameters['LiteralPath'] = $stack.Pop()
foreach($folder in Get-ChildItem @PSBoundParameters) {
$stack.Push($folder)
$count = 0
$size = 0
foreach($file in $folder | Get-ChildItem -File -Force) {
$count++
$size += $file.Length
}
$indexer[$folder.FullName] = [Tree]@{
FullName = $folder.FullName
Count = $count
Size = $size
}
$parent = $folder.Parent
while($parent -and $indexer.Contains($parent.FullName)) {
$indexer[$parent.FullName].AddSize($size)
$parent = $parent.Parent
}
}
}
$output = $indexer.PSBase.Values
if($output.Count) {
$output.SetFriendlySize()
$output
}
$indexer.Clear()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment