As system administrators or power users, we often need to keep an eye on the sizes of directories within our file systems – whether to monitor for space usage, during cleanups, or for inventory purposes. While Windows Explorer can provide this information, it becomes cumbersome when dealing with multiple folders or when we need to generate reports. The solution? PowerShell – a robust scripting shell that enables the automation of administrative tasks and more.
In this article, we’ll explore how you can use PowerShell to quickly retrieve the size of folders on your Windows system.
PowerShell: Your Tool for the Task
PowerShell is a step up from your traditional command-line interface. It’s equipped with a comprehensive scripting language and a set of tools that can manipulate every aspect of your Windows operating system.
Crafting the PowerShell Script to Get Folder Sizes
Below is a PowerShell script that uses the FileSystemObject
COM object to retrieve folder sizes and outputs the results in a sorted table, showing sizes in megabytes. Here’s a breakdown of the script:
# Create a FileSystemObject COM object
$fso = new-object -com Scripting.FileSystemObject
# Get all directories, calculate their sizes, and sort them in descending order
gci -Directory `
| select @{l='Size'; e={$fso.GetFolder($_.FullName).Size}},FullName `
| sort Size -Descending `
| ft @{l='Size [MB]'; e={'{0:N2}' -f ($_.Size / 1MB)}},FullName
Let’s dissect this script:
$fso = new-object -com Scripting.FileSystemObject
: We initiate a new COM object of typeFileSystemObject
. This object provides access to the file system on the computer.gci -Directory
: Short forGet-ChildItem -Directory
, this cmdlet retrieves all directories (folders) in the current path.select @{l='Size'; e={$fso.GetFolder($_.FullName).Size}},FullName
: We then pipe the output from the previous command toselect
, which projects each directory into a new object that includes the size and full name of the directory.sort Size -Descending
: This command sorts the directories in descending order based on their size.ft @{l='Size [MB]'; e={'{0:N2}' -f ($_.Size / 1MB)}},FullName
: Finally, the output is formatted into a table (ft
is short forFormat-Table
) with two columns: “Size [MB]” which is formatted to show two decimal places, and “FullName”, which is the path of the directory.
Running the Script
To run this script, simply open PowerShell and paste the code into the console, then press Enter. The script will execute in your current directory. If you wish to check the sizes of folders in a different directory, navigate to that directory first using the cd
command or specify the path directly in the Get-ChildItem
cmdlet.