'PowerShell Script to Get a Directory Total Size

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?



Solution 1:[1]

If you are interested in including the size of hidden and system files then you should use the -force parameter with Get-ChildItem.

Solution 2:[2]

Here's quick way to get size of specific file extensions:

(gci d:\folder1 -r -force -include *.txt,*.csv | measure -sum -property Length).Sum

Solution 3:[3]

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

Solution 4:[4]

To refine this answer by @JaredPar to be expanded and more performant:

function Get-DirectorySize() {
  param ([string]$root = $(Resolve-Path .))
  Get-ChildItem $root -Recurse -File |
    Measure-Object -Property Length -Sum |
    Select-Object -ExpandProperty Sum
}

Or, to make it more convenient for use explore type data:

Update-TypeData -TypeName System.IO.DirectoryInfo -MemberType ScriptProperty -MemberName Size -Value {
  Get-ChildItem $this -Recurse -File |
    Measure-Object -Property Length -Sum |
    Select-Object -ExpandProperty Sum
}

Then use by Get-ChildItem | Select-Object Name,Length,Size

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Keith Hill
Solution 2 Gordon Bell
Solution 3 youfoobar
Solution 4 carrvo