Friday, March 8, 2013

PowerShell - Calculate size for a folder/drive/item


One of the tasks an administrator or help-desk has been doing for ages is to calculate the size of a folder or drives or an item. Recently i had to work on a script that require space calculation, so i thought i should share the information as it could be handy for the new learners :-)

Here's the small code you can use:

 (Get-ChildItem -Path 'Folder/Drive Path' -Recurse | Measure-Object -Sum Length).sum /1GB

The above command will provide you the output in GB (gigabytes).

Let's understand how it works

 (Get-ChildItem -Path 'Folder/Drive Path' -Recurse | Measure-Object -Sum Length).sum /1GB

The () used above is to contain the command that will calculate the size of the object for you.

So what's running in the ()

(Get-ChildItem -Path 'Folder/Drive Path' -Recurse | Measure-Object -Sum Length).sum /1GB

As the name suggest, the command will get the child items in the Path specified.

Check TechNet Article to find more :

Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory. You can specify folder on the local disk or a network share where you have the access to read the data. For ex: D:\ , c:\foldertoread or \\calculate\foldersize or c:\yourfile.docx

Gets the items in the specified locations and in all child items of the locations.

In Windows PowerShell 2.0 or earlier versions of Windows PowerShell, the Recurse parameter works only when the value of the Path parameter is a container that has child items, such as c:\windows and not when it is an item does not have child item, such as C:\Windows\*.exe

Ok, now we have the path and PowerShell now knows what and where to look. 

This is used to pipe the output to the next command.

Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files of text
Check TechNet article for more details

Displays the sum of the values of the specified properties 

Is the file size of the item.

Will give you the sum total of the all the items accessed by PowerShell in the ().

/1Gb or /1Mb or /1Kb 
This will divide the size into GB, MB or KB.

OK, now we have understood the command so let's use it as a script 

$Path = Read-host 'Provide the path to calculate the size'

$TotalSize = (Get-ChildItem -Path $Path -Recurse | Measure-Object -Sum Length).sum

$SizeinGB = $TotalSize /1GB
$SizeinMB = $TotalSize /1MB
$SizeinKB = $TotalSize /1KB

Write-Host "$SizeinGB GB , $SizeinMB MB, $SizeinKB KB"

Copy the code and save the file as .ps1 ;-)

Thanks for reading it, i hope you find it useful.

No comments:

Post a Comment