Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 564
Jedi Master Spooky Avatar asked Apr 30 '09 20:04

Jedi Master Spooky


People also ask

How do I get a list of folder sizes?

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.

How do I count the number of files in a directory in PowerShell?

To get count files in the folder using PowerShell, Use the Get-ChildItem command to get total files in directory and use measure-object to get count files in a folder.

How can I see the size of a folder in Windows?

Go to Windows Explorer and right-click on the file, folder or drive that you're investigating. From the menu that appears, go to Properties. This will show you the total file/drive size. A folder will show you the size in writing, a drive will show you a pie chart to make it easier to see.


1 Answers

Try the following

function Get-DirectorySize() {
  param ([string]$root = $(resolve-path .))
  gci -re $root |
    ?{ -not $_.PSIsContainer } | 
    measure-object -sum -property Length
}

This actually produces a bit of a summary object which will include the Count of items. You can just grab the Sum property though and that will be the sum of the lengths

$sum = (Get-DirectorySize "Some\File\Path").Sum

EDIT Why does this work?

Let's break it down by components of the pipeline. The gci -re $root command will get all items from the starting $root directory recursively and then push them into the pipeline. So every single file and directory under the $root will pass through the second expression ?{ -not $_.PSIsContainer }. Each file / directory when passed to this expression can be accessed through the variable $_. The preceding ? indicates this is a filter expression meaning keep only values in the pipeline which meet this condition. The PSIsContainer method will return true for directories. So in effect the filter expression is only keeping files values. The final cmdlet measure-object will sum the value of the property Length on all values remaining in the pipeline. So it's essentially calling Fileinfo.Length for all files under the current directory (recursively) and summing the values.

like image 165
JaredPar Avatar answered Nov 03 '22 11:11

JaredPar