Wednesday, 26 March 2014

Get Folder Size (including subfolders) with Powershell

The method for obtaining the size of all items within a folder using Windows Powershell is unfortunately not as straight forward as it probably should be. The method outlined below is very useful for querying multiple folders to determine the size of all items inside, including all subfolders and files.

$dir = "C:\temp"
$totaldirsize = (get-childitem $dir -recurse -force | measure-object -property length -sum)

The first variable sets the directory that we wish to query - in this example it is C:\temp.

Next, we use a get-childitem to query the directory. The -recurse and -force switches mean that all sub directories and files are also included. We then pipe the results to measure-object and calculate the length of each child item (which is actually the size in bytes) and use the -sum switch to add them all up.

If you run the above command, and then look at the $totaldirsize variable, you will see something like below;

PS C:\> $totaldirsize

Count    : 38
Average  : 
Sum      : 51652089
Maximum  : 
Minimum  : 

Property : length

So from this we can see there are 38 items in total in the C:\temp directory, and the sum of all files is 51652089 bytes. To make this more useful, we can easily convert this value to KB, MB or GB

$mbsize = $totaldirsize.sum / 1MB

If we now look at $mbsize, we'll usually have an integer with a large number of decimal places. In this example, the result I got was 49.2592706680298. So as a final step, I'd like to round this number to 2 decimal places

$mbsize2 = "{0:N2}" -f $mbsize

Now if we look at the value of $mbsize2, the result is 49.26.

You can change the 2 in {0:N2} to any other digit to round the number to that many places after the decimal point.

No comments:

Post a Comment