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 all 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 {
   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.

Examples

Run the script:
PS C:\> ./diruse.ps1

“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.
Windows CMD: DIRUSE - Display disk usage.


 
Copyright © SS64.com 1999-2019
Some rights reserved