Skip to content

Instantly share code, notes, and snippets.

@nvnivs
Last active August 29, 2015 14:24
Show Gist options
  • Save nvnivs/9a080599fa93211f48c8 to your computer and use it in GitHub Desktop.
Save nvnivs/9a080599fa93211f48c8 to your computer and use it in GitHub Desktop.
Calculates the total size used by child folders of the specified location
function Get-TreeLength {
<#
.SYNOPSIS
Calculates the total size used by child folders of the specified location
.PARAMETER path
The root path
.PARAMETER depth
How many levels deep in the folder structure to go.
Defaults to 0, displays sizes of all subfolders of path
The higher the depth value is the slower it will be to fetch the inital
folder list needs to iterate through more levels
.EXAMPLE
Import-Module .\FileUtils -force; Get-TreeLength c:\test-folder
Returns the size of each folder in c:\test-folder
.EXAMPLE
ipmo .\FileUtils -force; Get-TreeLength c:\test-folder -depth 1
Returns the size of the child folders of the folders inside c:\test-folder
.EXAMPLE
ipmo .\FileUtils.psm1 -force; Get-TreeLength c:\test-folder -depth 0 | Export-Csv c:\test-folder-length.csv
Pipes the output to a csv file
#>
[CmdletBinding()]
param(
[parameter(position=0, mandatory=$true)]
[string]$path,
[ValidateRange(0,2)]
[int]$depth
)
GetFolders $path 0 $depth |
% {
New-Object PsObject -Property @{
"FullName" = $_;
"length" = GetRobocopyDirSize $_
}
}
}
function GetFolders {
<#
.SYNOPSIS
Recursively iterates through folders to match the depth
#>
[CmdletBinding()]
param(
[parameter(position=0, mandatory=$true)]
[string]$path,
[parameter(position=1, mandatory=$true)]
[int]$currentDepth,
[parameter(position=2, mandatory=$true)]
[int]$depth
)
Write-Verbose "Fetching child folders of $($path)"
$currentDepth++
gci $path |
? { $_.PSIsContainer } |
% {
if ($currentDepth -gt $depth) {
Write-Output $_.FullName
}
else {
GetFolders $_.FullName $currentDepth $depth
}
}
}
function GetRobocopyDirSize {
<#
.SYNOPSIS
Uses robocopy to determine a dir size, which is much faster than windows
#>
[CmdletBinding()]
param(
[parameter(position=0, mandatory=$true)]
[string]$path
)
[string]$result = robocopy /b /l /mir $path "c:\8c97b9e1-0f72-428e-9ab2-5017a6353182" /r:0 /w:0 /ns /nc /nfl /ndl /njh /bytes
if (-not ($lastexitcode -eq 16)) {
$pos = $result.IndexOf("Bytes : ")
$start = $pos + 8
$length = $result.Length
$end = $length - $start
$newstring = $result.Substring($start, $end)
$newstring = $newstring.Trim()
return [long]$newstring.Split()[0]
}
else {
Write-Error "Cannot access $path"
}
}
Export-ModuleMember -function Get-TreeLength
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment