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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#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.
1 2 3 |
$startDirectory = '\\sharename\dir1\dir2\' |
(Visited 36,093 times, 3 visits today)
Very useful. Thank you!
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
}
Nice! Thanks!
Thanks for this, really helpful.
But is there a way to add lastwritetime in the script?
Yes, Get-ChildItem can list the LastWriteTime of a file:
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7
Great post. Thanks !
Thanks, you saved my time