How to retrieve folder sizes using Windows PowerShell

good to read @Freshers.in

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:

  1. $fso = new-object -com Scripting.FileSystemObject: We initiate a new COM object of type FileSystemObject. This object provides access to the file system on the computer.
  2. gci -Directory: Short for Get-ChildItem -Directory, this cmdlet retrieves all directories (folders) in the current path.
  3. select @{l='Size'; e={$fso.GetFolder($_.FullName).Size}},FullName: We then pipe the output from the previous command to select, which projects each directory into a new object that includes the size and full name of the directory.
  4. sort Size -Descending: This command sorts the directories in descending order based on their size.
  5. ft @{l='Size [MB]'; e={'{0:N2}' -f ($_.Size / 1MB)}},FullName: Finally, the output is formatted into a table (ft is short for Format-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.

Author: user