I have found several resources that use the following script to get folder sizes
$colItems = (Get-ChildItem $startFolder -recurse | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object) foreach ($i in $colItems) { $subFolderItems = (Get-ChildItem $i.FullName | Measure-Object -property length -sum) $i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB" }
The problem with that is it also lists the subdirectories ie:
c:\test\1 -- 10mb c:\test\1\folder -- 10mb c:\test\1\folder\deep -- 5mb c:\test\1\folder\tuna -- 5mb c:\test\2 -- 20bm c:\test\2\folder -- 20mb c:\test\2\folder\deep -- 10mb c:\test\2\folder\tuna -- 10mb
I think you know see where I am going. What I am looking for is just the parent folder's results... SO:
c:\test\1 -- 10mb c:\test\2 -- 20mb
How can this be accomplished with Powershell? ....
You can use the Get-ChildItem ( gci alias) and Measure-Object ( measure alias) cmdlets to get the sizes of files and folders (including subfolders) in PowerShell.
Open a file explorer window and right-click on the 'Name' field at the top. You'll see some options – specifically, options, that let you pick what sort of info you want to see about your folders. Select Size and the property will appear on the far right of your window.
Substitute dir /A:D. /B /S > FolderList. txt to produce a list of all folders and all subfolders of the directory. WARNING: This can take a while if you have a large directory.
Right-click on the folder you want to view the size in File Explorer. Select “Properties.” The File Properties dialogue box will appear displaying the folder “Size” and its “Size on disk.” It will also show the file contents of those particular folders.
You need to get the total contents size of each directory recursively to output. Also, you need to specify that the contents you're grabbing to measure are not directories, or you risk errors (as directories do not have a Length
parameter).
Here's your script modified for the output you're looking for:
$colItems = Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object foreach ($i in $colItems) { $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 / 1MB) + " MB" }
This simple solution worked for me as well.
powershell -c "Get-ChildItem -Recurse 'directory_path' | Measure-Object -Property Length -Sum"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With