Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 34 ยท Projects

Project: File Organizer

Build a safe file organizer in PowerShell: classify files by extension, preview with -WhatIf, handle name collisions and keep an undo log. Includes a virtual file system model.

Every Downloads folder ends up as a heap: photos, PDFs, installers, zip files, all mixed together. A file organizer sorts them into folders by type. It is also the best project for learning safe automation, because a script that moves hundreds of files can do real damage if it has a bug. So this project is less about moving files and more about the habits that make moving them safe: a preview mode, collision handling and an undo log.

The real script touches your disk, so it is shown as read-only PowerShell. A JavaScript virtual file system (a set of paths held in memory) lets you run the same logic safely in your browser. It is a stand-in that models the algorithm, not PowerShell and not a real disk.

The safety rules

Safe by design

Preview first -WhatIf shows what would happen.
Never overwrite A name clash gets a new name.
Keep an undo log Record every move so you can reverse it.
Stay in scope Touch only the folder you were given.

Automate the boring part, not the risk.

1 / 2

Step 1: a category lookup

We describe the categories once, as a hashtable of lists, and turn it into a fast lookup from extension to category. Using [ordered] keeps the categories in the order we wrote them (see Arrays and Hashtables):

POWERSHELL
$categories = [ordered]@{
    Images    = '.jpg', '.jpeg', '.png', '.gif', '.svg', '.webp'
    Documents = '.pdf', '.doc', '.docx', '.txt', '.md', '.xlsx', '.pptx'
    Archives  = '.zip', '.7z', '.tar', '.gz'
    Audio     = '.mp3', '.wav', '.flac'
    Video     = '.mp4', '.mkv', '.mov'
}

$lookup = @{}
foreach ($name in $categories.Keys) {
    foreach ($extension in $categories[$name]) {
        $lookup[$extension] = $name
    }
}

function Get-FileCategory {
    param([string]$Extension)
    $key = $Extension.ToLowerInvariant()
    if ($lookup.ContainsKey($key)) { $lookup[$key] } else { 'Other' }
}

Hashtable keys are case-insensitive in PowerShell by default, but normalizing with ToLowerInvariant() makes the intent clear. Files with an unknown or missing extension go to Other, so nothing is left behind and nothing is lost.

Step 2: support -WhatIf the right way

The pattern for a safe command is built into advanced functions and scripts. Add [CmdletBinding(SupportsShouldProcess)] and wrap each change in $PSCmdlet.ShouldProcess(). With -WhatIf it prints what would happen and returns $false; with -Confirm it asks for each action (details in Advanced Functions).

POWERSHELL
[CmdletBinding(SupportsShouldProcess)]
param(
    [Parameter(Mandatory)]
    [string]$Source,

    [string]$LogName = 'organizer-undo.json'
)

$logPath = Join-Path $Source $LogName
$moves = [System.Collections.Generic.List[object]]::new()

$files = Get-ChildItem -LiteralPath $Source -File | Where-Object Name -ne $LogName

foreach ($file in $files) {
    $category  = Get-FileCategory -Extension $file.Extension
    $targetDir = Join-Path $Source $category
    $target    = Join-Path $targetDir $file.Name

    if ($PSCmdlet.ShouldProcess($file.FullName, "Move to $category")) {
        New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
        Move-Item -LiteralPath $file.FullName -Destination $target
        $moves.Add([pscustomobject]@{ From = $file.FullName; To = $target })
    }
}

Run ./Organize-Files.ps1 -Source ~/Downloads -WhatIf first. The output looks like What if: Performing the operation "Move to Images" on target "โ€ฆ\photo.jpg". for each file, and nothing changes on disk. Because the moves list stays empty under -WhatIf, no log is written either, which is what you want from a dry run. Two details matter. The log file lives in the source folder, so we exclude it from the scan. And we list only the top level, because -Recurse would also pull files back out of the category folders we create.

Step 3: never overwrite a file

Move-Item fails if the destination exists (unless you use -Force, which overwrites it, and we never want that). Make the name unique by adding a counter before the extension:

POWERSHELL
function Get-UniquePath {
    param([string]$Path)
    if (-not (Test-Path -LiteralPath $Path)) { return $Path }

    $directory = Split-Path -Path $Path -Parent
    $base      = [System.IO.Path]::GetFileNameWithoutExtension($Path)
    $extension = [System.IO.Path]::GetExtension($Path)
    $counter   = 1
    do {
        $candidate = Join-Path $directory "$base ($counter)$extension"
        $counter++
    } while (Test-Path -LiteralPath $candidate)
    $candidate
}

Call it just before moving: $target = Get-UniquePath -Path $target. Under -WhatIf, nothing has been moved yet, so two files that would collide with each other are not detected in a dry run. A careful script also tracks the targets it has already planned, which the stand-in below does.

Step 4: write the undo log

After the loop, save what happened. The log records the exact From and To of every move:

POWERSHELL
if ($moves.Count -gt 0) {
    ConvertTo-Json -InputObject @($moves) | Set-Content -LiteralPath $logPath -Encoding utf8
    Write-Verbose "Saved undo log to $logPath"
}

Note -InputObject @($moves): if you pipe a list into ConvertTo-Json, PowerShell unrolls it, and a list with one item becomes a single JSON object instead of an array. Passing it as -InputObject keeps the array shape (see CSV, JSON and XML). To undo, read the log and move everything back in reverse order:

POWERSHELL
$log = Get-Content -LiteralPath $logPath -Raw | ConvertFrom-Json
[array]::Reverse($log)
foreach ($move in $log) {
    if ($PSCmdlet.ShouldProcess($move.To, "Move back to $($move.From)")) {
        Move-Item -LiteralPath $move.To -Destination $move.From
    }
}

Reverse order matters when moves depend on each other, for example when a name was made unique because an earlier move occupied it. In a production script, check that $move.To still exists and $move.From does not, and report anything that changed since.

The stand-in, part one: classify and preview

The virtual file system is a Set of path strings. organize follows the same steps as the script: list top-level files, classify, make names unique, and either print "What if" lines or really move. The first demo shows a dry run followed by a real run.

JS Stand-in: preview, then organize

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

No output.

The dry run printed one line per file and left the set untouched; the real run moved everything. The file setup.exe went to Other, because we did not list .exe, and notes has no extension at all, so it went there too. The .JPG in capitals was matched thanks to toLowerCase().

The stand-in, part two: collisions and undo

Now we check the two safety nets. After a first run, a new file named like one already organized arrives, so the second run must avoid a collision. The undo function replays the log in reverse and then we verify that the file set is exactly what it was before.

JS Stand-in: unique names and undo

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

No output.

The second run did not overwrite Inbox/Images/photo.jpg: the newcomer became photo (1).jpg. Undoing the runs in reverse order brought everything back, which is exactly why the log is replayed backwards.

Ideas to extend it

  • Add a -Recurse option guarded by a depth limit, and skip the category folders themselves.
  • Sort by date instead of type, with $file.LastWriteTime.ToString('yyyy-MM') as the folder name.
  • Add a -Exclude list for files that must stay where they are.
  • Schedule it with a scheduled task, but only after you have used -WhatIf for a week.
  • Add Pester tests with TestDrive: that create files, run the script and check the folders (see Testing and Style with Pester).
  • Use Start-Transcript to keep a human-readable record next to the JSON log.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does adding SupportsShouldProcess to CmdletBinding give your script?

    SupportsShouldProcess adds -WhatIf and -Confirm. You decide where they apply by wrapping each change in an if with $PSCmdlet.ShouldProcess().
  2. 2. Why is the undo log replayed in reverse order?

    A later move can depend on the state created by an earlier one, for example a name that was made unique. Undoing in reverse restores states in the right order.
  3. 3. Why does the script avoid Move-Item -Force for name clashes?

    Overwriting silently destroys the older file. A unique name keeps both files.
  4. 4. Under -WhatIf, why is no undo log written?

    ShouldProcess returns false under -WhatIf, so the move and the list.Add are skipped. An empty list means no log.
  5. 5. Why does ConvertTo-Json -InputObject @($moves) keep a one-item list as an array?

    The pipeline sends items one by one, so ConvertTo-Json cannot know there was a list. -InputObject passes the whole array at once.

Summary

  • Classify with a hashtable lookup from extension to category, with Other as the safe default.
  • Use [CmdletBinding(SupportsShouldProcess)] and $PSCmdlet.ShouldProcess() so -WhatIf previews every change.
  • Never overwrite: make destination names unique and track targets already planned.
  • Log every move as From and To, save it with ConvertTo-Json -InputObject @($moves), and undo in reverse order.
  • Stay in scope: list only the source folder, and exclude your own log file.
  • The JavaScript virtual file system models the algorithm; the PowerShell script is shown read-only.

Next: Project: Bulk User Report from CSV.