Many of us are always looking at what is using space on a server because one of the monitoring solutions has such as SolarWinds, SCOM or LabTech have sent an alert that the C:\ Drive has gone below 15% or whatever threshold you have set. Many of these are enterprise applications so you may not be running it but I put together a script that not only shows you the folder size but also the file size within the folder.

When you run the script, it prompts you for a location. In the example below, I specified “C:\Inetpub” on an Exchange 2019 server and this was the output:

Display the folder size and the files contained within it using powershell

I added arrows to show you the main folders and then all the files within the folders. The script also works against a remote computer, I ran it against another Exchange 2019 server using PowerShell ISE as shown below, if you notice, it lists all the contents of the folder and not the folder itself because we didn’t specify a path higher such as C:\ only:

Display the folder size and the files contained within it using powershell


The script is rather long but works from PowerShell ISE or as a saved PS1 file, here is the script below:

# Function to calculate folder size
function Get-FolderSize {
    param (

    $folder = Get-Item $folderPath
    $size = 0

    # Calculate size for each file in the folder
    Get-ChildItem -Recurse $folder.FullName | ForEach-Object {
        $size += $_.Length

    return $size

# Function to format bytes into a human-readable format
function Format-Size {
    param (

    $units = @("B", "KB", "MB", "GB", "TB")
    $index = 0

    while ($size -ge 1KB -and $index -lt $units.Length) {
        $size /= 1KB

    return "{0:N2} {1}" -f $size, $units[$index]

# Get folder path from the user or use a default path
$folderPath = Read-Host "Enter folder path (or press Enter for the current directory):"
if (-not $folderPath) {
    $folderPath = Get-Location

# Get all folders and files in the specified path
$items = Get-ChildItem -Path $folderPath -Recurse | Where-Object { $_.PSIsContainer -or $_.Length -gt 0 }

# Calculate sizes and store in custom object
$sizeInfo = $items | ForEach-Object {
        Name = $_.FullName
        Size = if ($_.PSIsContainer) { Get-FolderSize $_.FullName } else { $_.Length }

# Sort by size in descending order
$sortedSizeInfo = $sizeInfo | Sort-Object -Property Size -Descending

# Display the results
$sortedSizeInfo | ForEach-Object {
    $formattedSize = Format-Size -size $_.Size
    Write-Host ("{0,-80} {1}" -f $_.Name, $formattedSize)

The script runs quite quickly, all depending on the folder you specify.

Hope it helps.

Discover more from Everything-PowerShell

Subscribe now to keep reading and get access to the full archive.

Continue reading