Using PowerShell To List Folders And Sizes

One of the things I run into regularly when dealing with storage is needing to know the sizes of folders in a directory.  For example, if something filled up a drive over night, and you have 50 directories on that drive, which one did it?

Thankfully, PowerShell makes it easy to list out all of the folders in a directory, and calculate the size of the contents in each folder.  Just run the below script, and change the $startDirectory path to the directory you want to check.

#gets the size of every directory under the $startDirectory directory
#can sometimes be a little slow if a directory has a lot of folders in it
$startDirectory = 'E:\MSSQL\Backups\'

#gets a list of folders under the $startDirectory directory
$directoryItems = Get-ChildItem $startDirectory | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object

#loops throught he list, calculating the size of each directory
foreach ($i in $directoryItems)
{
    $subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
    $i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1GB) + " GB"
}

This nice thing about this script is that it also works on network paths (providing you have appropriate permissions).  To get the file sizes on a network share, simply change the $startDirectory path to the share you want to check.

$startDirectory = '\\sharename\dir1\dir2\'

 

(Visited 38,717 times, 1 visits today)

7 thoughts on “Using PowerShell To List Folders And Sizes”

  1. sageofwestcott

    In case it’s of any use to somebody, I tweaked your code to show both the size of the directories and the associated file count:

    foreach ($i in $directoryItems)
    {
    $fcount = (get-childitem “$startDirectory$i” | measure-object ).count
    $subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
    $i.FullName + ” Size: ” + “{0:N2}” -f ($subFolderItems.sum / 1GB) + ” GB ” + ” Filecount: ” + $fcount
    }

Comments are closed.