Monthly Archive

Categories

Get Folder sizes

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

Comments are closed.