Reclaim Disk Space: Find Large Directories with PowerShell on Windows
Are you constantly running out of disk space? Do you suspect there are hidden giants consuming your precious storage? Manually sifting through folders to find the culprits can be a tedious and time-consuming task. Fortunately, PowerShell comes to the rescue!
In this blog post, I’ll share a simple yet powerful PowerShell script that helps you identify the largest directories on your system, allowing you to quickly pinpoint where your disk space is being used most.
The PowerShell Script
Here’s the PowerShell script you can use. Copy and paste this into a text editor and save it as a .ps1
file (e.g., FindLargeDirectories.ps1
).
# Define the minimum directory size in bytes (500 MB)
# 1 MB = 1024 * 1024 bytes
$minSizeInBytes = 500 * 1024 * 1024
# Define the output file path
$outputFilePath = "C:\Temp\LargeDirectoriesList.txt" # Changed file name for clarity
# Define the root directory to start the search from
# For example, to search the entire C: drive, use "C:\"
# To search a specific folder, use "C:\Users\YourUser\Documents"
$rootDirectory = "C:\" # IMPORTANT: Change this to the directory you want to scan
Write-Host "Scanning directory: $rootDirectory for directories larger than $($minSizeInBytes / 1MB) MB..."
Write-Host "Results will be saved to: $outputFilePath"
try {
# Get all directories recursively from the specified root directory
Get-ChildItem -Path $rootDirectory -Recurse -Directory -ErrorAction SilentlyContinue |
ForEach-Object {
$dir = $_
# Calculate the total size of files within the current directory and its subdirectories
# This can be time-consuming for very large directories or many directories.
$size = (Get-ChildItem -Path $dir.FullName -Recurse -File -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum
# Create a custom object with directory path and calculated size
[PSCustomObject]@{
Path = $dir.FullName
Size = $size
}
} |
# Filter directories that are larger than the defined minimum size
Where-Object { $_.Size -gt $minSizeInBytes } |
# Select the Path and calculated Size properties
Select-Object @{Name="Size (MB)"; Expression={"{0:N2}" -f ($_.Size / 1MB)}}, Path |
# Sort the results by Size in descending order (largest to smallest)
Sort-Object -Property "Size (MB)" -Descending |
# Format the output for readability
Format-Table -AutoSize |
# Convert to string and save to the output file
Out-String -Stream |
Set-Content -Path $outputFilePath -Encoding UTF8
Write-Host "Script completed successfully. Large directory list saved to '$outputFilePath'."
}
catch {
Write-Error "An error occurred: $($_.Exception.Message)"
}
How to Use the Script
Save the Script: Copy the code above and paste it into a plain text editor (like Notepad). Save the file with a
.ps1
extension (e.g.,FindLargeDirectories.ps1
).Customize Variables:
$rootDirectory
: This is the most important variable to change. Set it to the drive or folder you want to scan. For example, to scan your entireC:
drive, use"C:\"
. To scan your Documents folder, use"C:\Users\YourUsername\Documents"
.$minSizeInBytes
: By default, the script looks for directories larger than 500 MB. You can adjust this value if you need to find larger or smaller directories.$outputFilePath
: This specifies where the results will be saved. The default isC:\Temp\LargeDirectoriesList.txt
.
Run the Script:
Open PowerShell as an Administrator. (Right-click on the PowerShell icon and select “Run as administrator”).
Navigate to the directory where you saved your
.ps1
file using thecd
command (e.g.,cd C:\Scripts
).Execute the script by typing:
.\FindLargeDirectories.ps1
View Results: Once the script finishes, open the
LargeDirectoriesList.txt
file at the specified$outputFilePath
to see a list of your largest directories, sorted from largest to smallest.
How the Script Works
Let’s break down the key parts of this PowerShell script:
$minSizeInBytes
: Defines the threshold for what’s considered a “large” directory.$rootDirectory
: Sets the starting point for the scan.Get-ChildItem -Path $rootDirectory -Recurse -Directory
: This command is the workhorse. It recursively finds all directories starting from your specified$rootDirectory
.ForEach-Object { ... }
: For each directory found, the script performs an action.Get-ChildItem -Path $dir.FullName -Recurse -File | Measure-Object -Property Length -Sum
: This is the crucial part for calculating directory size. For each directory, it recursively finds all files within that directory and its subdirectories and then sums up theirLength
(size in bytes).Where-Object { $_.Size -gt $minSizeInBytes }
: Filters the results, keeping only those directories whose calculated size exceeds your defined minimum.Select-Object @{Name="Size (MB)"; Expression={"{0:N2}" -f ($_.Size / 1MB)}}, Path
: Formats the output. It converts the size from bytes to megabytes (MB) and formats it to two decimal places, alongside the full path of the directory.Sort-Object -Property "Size (MB)" -Descending
: Arranges the results so the largest directories appear at the top.Format-Table -AutoSize | Out-String -Stream | Set-Content -Path $outputFilePath
: Takes the formatted data, converts it into a string, and saves it to the specified text file.try { ... } catch { ... }
: Basic error handling to catch any issues during execution and display a helpful message.
Conclusion
This PowerShell script is a fantastic tool for anyone looking to manage their disk space more effectively. By quickly identifying large directories, you can make informed decisions about what to keep, move, or delete, helping you keep your system lean and efficient.
Do you have any other PowerShell tips or tricks for managing disk space? Share them in the comments below!