How-to: DIRUSE, a PowerShell script to list directory sizes

The old DirUse Resource kit utility can still be run in PowerShell to display disk usage for multiple subdirectories, but all it will do is display text it won’t provide any PowerShell objects we can manipulate.

The script below is pure PowerShell and is kept as simple as possible to make it understandable - you may want to build on this and turn it into an advanced function.

$folder = '\\server64\Users'

$DirUseArray = @()
# Get a list of first level sub-folders
$firstLevel = Get-ChildItem $folder -directory
$firstLevel | ForEach-Object {
   Echo "Reading $_"
   # Read the size of this folder and all its sub folders.
   $size = (
      Get-ChildItem $folder\$_\* -recurse
   ) | Measure-Object -property length -sum | Select-Object -expand sum
   # Convert from Bytes to GiB and round to 2 decimal places
   $size =  [math]::Round($(0 + $size /1GB),2)
   Echo $size
   # Add to an array
   $DirUseArray += New-Object PsObject -property @{
      'Folder' = $_
      'Size (GB)' = $size
$DirUseArray | Export-CSV -path C:\batch\DirUse.csv -NoTypeInformation

The main core of this script is the line (Get-ChildItem $folder\* -recurse) | measure-object -property length -sum which enumerates all the files in a folder and then passes them to Measure-Object to get the total size.

Run the script:

PS C:\> ./diruse.ps1

To just get the total size without enumerating any top level folders:

function Get-FolderSize {

Param (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)] $Path
if ( (Test-Path $Path) -and (Get-Item $Path).PSIsContainer ) {
   $FolderSize = Get-ChildItem $Path -Recurse -Force -ErrorAction SilentlyContinue |
   Measure-Object -Property Length -Sum
   $FolderSizeGB = '{0:N2}' -f ($FolderSize.Sum / 1GB)
      'Path' = $Path
      'Size(GB)' = $FolderSizeGB

Run the script:

PS C:\> Get-FolderSize 'C:\demo'

“The size and age of the Cosmos are beyond ordinary human understanding. Lost somewhere between immensity and eternity is our tiny planetary home. In a cosmic perspective, most human concerns seem insignificant, even petty. And yet our species is young and curious and brave and shows much promise.” ~ Carl Sagan

Related PowerShell Cmdlets

Get-ChildItem - Get child items (contents of a folder or registry key).
Measure-Object - Measure the properties of an object.
Equivalent Windows CMD command: DIRUSE - Display disk usage.
Equivalent Linux bash command: du - Disk Usage

Copyright © 1999-2024
Some rights reserved