Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 34 ยท Projects

Project: Disk and Folder Report

Build a disk and folder report in PowerShell: scan files, group by extension, bucket by size, sort, format readable sizes and export to CSV. Includes a runnable JS model.

"Where did my disk space go?" is one of the oldest questions in administration, and it is a perfect first project. You need nearly everything from the course so far: files, the pipeline, grouping, calculated properties, sorting, formatting and CSV export. In this project you will build a report script that scans a folder, shows which file types use the most space, lists the biggest files, and saves the numbers to a CSV file.

The real script uses Get-ChildItem and needs a file system, so it is shown as read-only code. A JavaScript stand-in runs the same steps on a list of sample files, so you can edit the data and watch the report change. The stand-in models the logic; it does not scan a real disk.

The plan

Five steps to a report

Scan Get every file with its size.
Group Total the size per extension.
Rank Sort, and keep the biggest.
Format Show KB, MB and GB, not raw bytes.

Format last, so the data stays usable.

1 / 2

The key design rule is the same one from Formatting and Output: keep real numbers in your objects as long as you can, and turn them into pretty text only at the very end. If you convert 1572864 to "1.5 MB" too early, you can no longer sort or add it correctly.

Step 1: scan the folder

POWERSHELL
param(
    [string]$Path = '.',
    [int]$Top = 5,
    [string]$CsvPath
)

$files = Get-ChildItem -LiteralPath $Path -Recurse -File -ErrorAction SilentlyContinue
"Scanned {0} files in {1}" -f $files.Count, (Resolve-Path -LiteralPath $Path)

-File returns only files, -Recurse walks all sub-folders, and -ErrorAction SilentlyContinue skips folders you are not allowed to open instead of filling the screen with red errors (see Errors, try/catch and ErrorAction). -LiteralPath means that names with [ or * are taken literally. Each file object has a Length property in bytes, an Extension, a FullName and a LastWriteTime.

Step 2: group by extension

Group-Object can group by a script block, which lets you normalize the extension (so .JPG and .jpg count together, and files without one get a label). Measure-Object -Sum adds up the sizes:

POWERSHELL
$byExtension = $files |
    Group-Object { if ($_.Extension) { $_.Extension.ToLowerInvariant() } else { '(none)' } } |
    ForEach-Object {
        $bytes = ($_.Group | Measure-Object -Property Length -Sum).Sum
        [pscustomobject]@{
            Extension = $_.Name
            Files     = $_.Count
            Bytes     = [long]$bytes
        }
    } |
    Sort-Object -Property Bytes -Descending

Notice that the result is a list of new objects with exactly the columns we want. This is the pattern of nearly every report: collect raw facts, then shape them with [pscustomobject]. See Group-Object, Measure-Object and ForEach-Object for a refresher.

Step 3: size buckets and the biggest files

A bucket is a coarse category such as small, medium and large. A switch with script-block conditions does the job:

POWERSHELL
function Get-SizeBucket {
    param([long]$Bytes)
    switch ($Bytes) {
        { $_ -lt 1MB }   { 'Small (< 1 MB)';   break }
        { $_ -lt 100MB } { 'Medium (< 100 MB)'; break }
        default          { 'Large (>= 100 MB)' }
    }
}

$buckets = $files |
    Group-Object { Get-SizeBucket -Bytes $_.Length } |
    Select-Object Name, Count

$biggest = $files | Sort-Object -Property Length -Descending | Select-Object -First $Top

PowerShell understands the size suffixes KB, MB, GB and TB as plain numbers (1MB is 1048576), so conditions stay readable. Remember break in each branch, because switch keeps testing the other branches otherwise.

Step 4: human-readable sizes

A small function formats bytes. It divides by 1024 until the number is small:

POWERSHELL
function Format-Size {
    param([long]$Bytes)
    $units = 'B', 'KB', 'MB', 'GB', 'TB'
    $value = [double]$Bytes
    $i = 0
    while ($value -ge 1024 -and $i -lt $units.Count - 1) {
        $value /= 1024
        $i++
    }
    '{0:N1} {1}' -f $value, $units[$i]
}

The -f operator formats the number with one decimal place (see Strings, Quoting and Here-Strings). Because this function returns text, you call it only when you display, using a calculated property:

POWERSHELL
$byExtension | Select-Object Extension, Files,
    @{ Name = 'Size'; Expression = { Format-Size $_.Bytes } } |
    Format-Table -AutoSize

Step 5: export the numbers

For a CSV file you want the exact Bytes, not the pretty text, because a spreadsheet can format it later:

POWERSHELL
if ($CsvPath) {
    $byExtension | Export-Csv -LiteralPath $CsvPath -NoTypeInformation -Encoding utf8
    Write-Verbose "Saved $CsvPath"
}

-NoTypeInformation removes a #TYPE line that Windows PowerShell 5.1 adds to the top of the file (in PowerShell 7 it is already the default, and the switch is harmless). Export-Csv quotes every field by default.

Putting it together

A good script separates collecting from showing. You could wrap steps 1 to 3 in a function that returns one report object, and keep the screen output in the script body. Then another script (or a Pester test, see Testing and Style with Pester) can reuse the function and ignore the formatting. The skeleton of the final script is:

POWERSHELL
$report = [pscustomobject]@{
    Path        = (Resolve-Path -LiteralPath $Path).Path
    TotalFiles  = $files.Count
    TotalBytes  = ($files | Measure-Object -Property Length -Sum).Sum
    ByExtension = $byExtension
    Buckets     = $buckets
    Biggest     = $biggest
}

The stand-in: run the same logic on sample data

The JavaScript below has a list of sample files, where each one has a path and a size in bytes, as if Get-ChildItem had returned them. It groups by extension, buckets by size, finds the biggest files and prints a readable table. Change a size or add a file and rerun.

JS Stand-in: group, bucket and rank

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at how the pieces match the PowerShell. The Map plays the role of Group-Object, the sum of Measure-Object, sort of Sort-Object, and slice(0, 3) of Select-Object -First 3. Normalizing the extension with toLowerCase() makes .JPG and .jpg land in one group, just like ToLowerInvariant() in the script.

Exporting a CSV in the stand-in

A CSV file is plain text: a header row, then one row per object, with fields separated by commas. Fields that contain a comma, a quote or a line break need quotes, and quotes inside them are doubled. Export-Csv does this for you; the model below shows how, and why you export raw bytes and a separate readable column only when someone needs it.

JS Stand-in: write the CSV text

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last two lines of the demo make a point that applies to Import-Csv too: every value comes back as text. Cast with [long] before you sort or add, or the string "9" will sort after "10".

Ideas to extend it

  • Add a -OlderThanDays parameter and list files whose LastWriteTime is older than that, to find cleanup candidates.
  • Report per top-level folder instead of per extension, by grouping on the first path segment under $Path.
  • Output the report as JSON with ConvertTo-Json -Depth 4, or as HTML with ConvertTo-Html, to mail it to a team.
  • Check drive free space with Get-PSDrive -PSProvider FileSystem and warn below a threshold.
  • Make the script a function with [CmdletBinding()], and add Pester tests that use TestDrive:.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the report keep the Bytes property as a number and format sizes only at the end?

    Formatting turns numbers into text. Sorting and summing need the real numbers, so format last, when you display.
  2. 2. What does Group-Object { ... } with a script block let you do?

    A script block is evaluated for each object, and the result becomes the group key. That is how .JPG and .jpg end up in one group.
  3. 3. What does -ErrorAction SilentlyContinue do on Get-ChildItem -Recurse in this script?

    Non-terminating errors for unreadable folders are suppressed, so the scan continues and the output stays clean.
  4. 4. A teammate reads your CSV with Import-Csv and sorts by Bytes. What must they remember?

    Import-Csv returns text for every column. Cast with [long] (or use a calculated property) so that 9 sorts before 10.

Summary

  • A report is a pipeline: scan with Get-ChildItem -Recurse -File, group with Group-Object, total with Measure-Object -Sum, sort, then format.
  • Build new objects with [pscustomobject] so each column is exactly what you want.
  • Keep sizes as numbers in Bytes; use a Format-Size function and calculated properties only for display.
  • Export raw numbers with Export-Csv; remember Import-Csv returns text.
  • The JavaScript demos model the same steps on sample data, and do not read a real disk.

Next: Project: Log Analyzer.