I need to get the size of a directory, recursively. I have to do this every month so I want to make a PowerShell script to do it.
How can I do it?
If you are interested in including the size of hidden and system files then you should use the -force parameter with Get-ChildItem.
Try the following
function Get-DirectorySize() {
param ([string]$root = $(resolve-path .))
gci -re $root |
?{ -not $_.PSIsContainer } |
measure-object -sum -property Length
}
This actually produces a bit of a summary object which will include the Count of items. You can just grab the Sum property though and that will be the sum of the lengths
$sum = (Get-DirectorySize "Some\File\Path").Sum
EDIT Why does this work?
Let's break it down by components of the pipeline. The gci -re $root
command will get all items from the starting $root
directory recursively and then push them into the pipeline. So every single file and directory under the $root
will pass through the second expression ?{ -not $_.PSIsContainer }
. Each file / directory when passed to this expression can be accessed through the variable $_
. The preceding ? indicates this is a filter expression meaning keep only values in the pipeline which meet this condition. The PSIsContainer method will return true for directories. So in effect the filter expression is only keeping files values. The final cmdlet measure-object will sum the value of the property Length on all values remaining in the pipeline. So it's essentially calling Fileinfo.Length for all files under the current directory (recursively) and summing the values.
Here's quick way to get size of specific file extensions:
(gci d:\folder1 -r -force -include *.txt,*.csv | measure -sum -property Length).Sum
Thanks to those who posted here. I adopted the knowledge to create this:
# Loops through each directory recursively in the current directory and lists its size.
# Children nodes of parents are tabbed
function getSizeOfFolders($Parent, $TabIndex) {
$Folders = (Get-ChildItem $Parent); # Get the nodes in the current directory
ForEach($Folder in $Folders) # For each of the nodes found above
{
# If the node is a directory
if ($folder.getType().name -eq "DirectoryInfo")
{
# Gets the size of the folder
$FolderSize = Get-ChildItem "$Parent\$Folder" -Recurse | Measure-Object -property length -sum -ErrorAction SilentlyContinue;
# The amount of tabbing at the start of a string
$Tab = " " * $TabIndex;
# String to write to stdout
$Tab + " " + $Folder.Name + " " + ("{0:N2}" -f ($FolderSize.Sum / 1mb));
# Check that this node doesn't have children (Call this function recursively)
getSizeOfFolders $Folder.FullName ($TabIndex + 1);
}
}
}
# First call of the function (starts in the current directory)
getSizeOfFolders "." 0