PowerShell for Windows Admins

Nov 29 2017   10:21AM GMT

Get Folder sizes

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

One problem that comes up quite often is how do you get folder sizes. One option is use Measure-Object but the problem with that approach is that its going to be a pretty slow process if you have a lot of folders. PowerShell doesn’t have a method of directly getting the folder size and you have to count through all of the sub-folders which becomes a very repetitive exercise.

If you’re prepared to use an old style VBScript approach you can use the FileSystem COM object like this

function Get-FolderSize {
 [CmdletBinding()]
param (
 [string]$path = 'C:\MyData'
 )

if (-not (Test-Path -Path $path)){
 Throw "$path - Path not found"
 }

$fso = New-Object -ComObject "Scripting.FileSystemObject"

Get-ChildItem -Path $path -Directory -Recurse |
foreach {
 
 $size = ($fso.GetFolder("$($PSItem.FullName)")).Size
 
 $props = [ordered]@{
 Name = $PSItem.Name
 Created = $PSItem.CreationTime
 FilePath = $PSItem.FullName
 SizeMB = [math]::Round( ($size / 1mb), 2)
 }

New-Object -TypeName PSObject -Property $props
 }

}

 

use as

Get-FolderSize -path <folder path>

if you want the subfolders immediately after their parent then add a sort

Get-FolderSize -path <folder path> | sort FilePath

and if you want to order by size then

Get-FolderSize -path <folder path> | sort SizeMB -Descending

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: