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\' |