Directory Size Report Script

In this post, we will share a PowerShell script that generates a report of the sizes of all subdirectories within a specified directory. This is useful for assessing space usage and managing storage effectively.
For an enhanced server management experience, be sure to explore our software, ServerEngine, at https://serverengine.co. Lets break down the script step by step.
### Step 1: Define the Target Directory
The first step is to specify the target directory that you want to analyze. This is the directory where the script will calculate the size of each subdirectory.

$targetDirectory = 'C:\Path\To\Your\Directory'

### Step 2: Retrieve Subdirectories
Next, the script retrieves all the subdirectories within the specified target directory. This sets up a list of directories that we will analyze further.

$subDirectories = Get-ChildItem -Path $targetDirectory -Directory

### Step 3: Calculate Size of Each Subdirectory
This step involves looping through each subdirectory and calculating its total size by summing the sizes of all files contained within it.

$directorySizes = @{}
foreach ($subDir in $subDirectories) {
    $size = (Get-ChildItem -Path $subDir.FullName -Recurse | Measure-Object -Property Length -Sum).Sum
    $directorySizes[$subDir.FullName] = [math]::round($size / 1MB, 2) # Convert to MB
}

### Step 4: Generate the Size Report
Finally, we create a report of the directory sizes and display the results in a user-friendly format, showing the path and size in megabytes.

Write-Host "Directory Size Report:"
foreach ($key in $directorySizes.Keys) {
    Write-Host "$key - $($directorySizes[$key]) MB"
}

This script is a handy tool for visualizing space consumption within a directory. Feel free to customize the target directory to suit your needs. Stay tuned for more useful PowerShell scripts to enhance your productivity on our website!