Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Windows Junction Manager

A portable PowerShell 7 tool and interactive terminal UI for managing Windows directory junctions (reparse points).

5 modules and 24 actions, driven by one shared catalog.

Windows Junction Manager creates, inspects, repairs, cleans, exports and restores junctions while keeping protected system and user-profile compatibility paths untouched. Every mutating action supports a dry-run preview.

What it does

AreaCapability
DiscoveryScan standard locations or any custom directory, inspect one junction, summarize health
LifecycleCreate, retarget with rollback, repair and remove junctions
CleanupRemove orphaned links, empty-target links, or both, with optional empty-target reclamation
InventoryJSON/CSV export, timestamped backup snapshots, import preview and guarded restore
SafetyProtected-path policy, dry-run everywhere, confirmation for destructive headless actions

How the pieces fit

flowchart TD
    A["JunctionManager.bat<br/>PATH pwsh launcher"] --> B["JunctionManager.ps1<br/>root entry point"]
    B --> C["src/menu.ps1<br/>CLI dispatcher + TUI"]
    C --> D["src/core/manifest.ps1<br/>load-order manifest"]
    D --> E["version.ps1"]
    D --> F["paths.ps1"]
    D --> G["junctions.ps1"]
    D --> H["operations.ps1"]
    D --> I["inventory.ps1"]
    D --> J["catalog.ps1"]
    D --> K["logger.ps1"]
    D --> L["ui-helpers.ps1"]
    C --> M["TUI surfaces"]
    C --> N["Headless CLI"]
    M --> O["5 modules / 24 actions"]
    N --> O

Junction status model

stateDiagram-v2
    [*] --> Active: target exists and contains files
    [*] --> StaleOrphaned: target directory missing
    [*] --> StaleEmpty: target exists but contains no files
    [*] --> Missing: inspected path does not exist
    [*] --> NotAJunction: path exists but is not a junction
    StaleOrphaned --> [*]: cleanup detaches the link
    StaleEmpty --> [*]: cleanup detaches the link, optional target reclaim
    Active --> [*]: remove detaches the link, target kept

Quick start

JunctionManager.bat
JunctionManager.bat --list
JunctionManager.bat --scan
JunctionManager.bat --clean-stale --dry-run

Where to go next

Requirements

  • Windows 11
  • PowerShell 7.x (pwsh)

No installation is required. The batch launchers use pwsh from PATH.

Getting started

Windows Junction Manager is a portable PowerShell 7 tool for Windows 11. It has no installer and no background service.

Requirements

RequirementNotes
Windows 11Junctions are a Windows reparse-point feature
PowerShell 7.xpwsh must be on PATH for the batch launchers
Local filesystemJunction links and targets must be local, not UNC network paths

Ordinary user-profile junctions usually work without elevation. Protected system locations are refused by policy, not by privilege.

Verify PowerShell

where pwsh
pwsh -NoProfile -Command "$PSVersionTable.PSVersion"

If pwsh is missing, install PowerShell 7 with your normal package manager and reopen the terminal. The project itself never embeds or hard-codes a PowerShell install path.

Launch the tool

Open the interactive terminal UI:

JunctionManager.bat

Run a headless command:

JunctionManager.bat --list

Invoke the root script directly if you prefer:

pwsh -NoProfile -File .\JunctionManager.ps1 --list

The launcher resolves its own folder, so the project can live anywhere.

First safe session

  1. Run JunctionManager.bat --list to confirm the catalog loads. You should see 5 modules and 24 actions.
  2. Run JunctionManager.bat --scan to discover junctions in the standard application locations.
  3. Press D in the TUI, or pass --dry-run on the CLI, before trying a mutating action.
  4. Inspect a single junction with --inspect <path> to confirm its status and target.
flowchart LR
    A[Launch] --> B[List catalog]
    B --> C[Scan locations]
    C --> D[Inspect a junction]
    D --> E{Change needed?}
    E -- No --> F[Stop]
    E -- Yes --> G[Dry-run preview]
    G --> H[Apply with confirmation]

Where files go

ArtifactLocation
Diagnostic logslogs\windows-junction-manager-YYYY-MM-DD.log when logging is enabled
Backup snapshotsbackups\junction-inventory-YYYYMMDD-HHmmss.json

Exports can be written anywhere you choose. Backups and logs are created relative to the project unless you pass an explicit export path.

Next steps

Interactive TUI

Launch the TUI with no arguments:

JunctionManager.bat

The interface uses a 256-color dark-terminal palette, a header with status pills, a module/action list, and a footer that shows context hints and the latest status message. Rendering degrades to plain text when output is redirected or NO_COLOR is set.

Screen layout

╭──────────────────────────────────────────────────────────────╮
│ ◆ Junction Manager › Main Menu (24 actions)     PS 7.4 · ADMIN │
╰──────────────────────────────────────────────────────────────╯

  ▸ [1] Scan & Inspect        6 actions │ Discover, inspect and classify junctions
    [2] Create & Manage       5 actions │ Create, retarget, repair and remove junctions
    [3] Clean & Repair        4 actions │ Remove stale links and reclaim empty targets
    [4] Backup & Export       5 actions │ Export inventory, back up and restore links
    [5] Settings & Safety     4 actions │ Protected paths, scan roots, logs and about

──────────────────────────────────────────────────────────────────
  ↑/↓ Move · Enter Open · 1-5 Jump · / Search · D Dry-Run · L Log · Q Quit

Keys

KeyMain menuModule menu
↑ / ↓Move between modulesMove between actions
k / jVim-style up/downVim-style up/down
Home / EndFirst / last moduleFirst / last action
EnterOpen moduleRun action
1–5Jump to moduleJump to action
/Open live searchOpen live search
DToggle dry-runToggle dry-run
LToggle diagnostic loggingToggle diagnostic logging
B / EscQuit or go backGo back
QQuitQuit

Header pills

PillMeaning
PS 7.xPowerShell major/minor version
ADMINCurrent session is elevated
STANDARDCurrent session is not elevated
DRY-RUNMutating actions preview only
LOGDiagnostic logging is active

Press / from either menu. Type to filter by action ID, label, module name or module ID. Use ↑/↓ to move, Enter to run the highlighted action, Backspace to edit, and Esc to return.

Search is the fastest way to reach a known action: clean, backup, protected, or an exact ID such as clean-stale-empty.

Dry-run mode

Press D to toggle dry-run. When enabled:

  • Create and retarget return a preview result.
  • Remove and cleanup report what would be detached.
  • Exports and backups report the destination without writing.
  • Empty-target deletion reports the target without removing it.

Dry-run is a per-session toggle in the TUI. On the CLI, pass --dry-run per command.

Logging

Press L to start or stop diagnostic logging. The footer toast shows the active log file name. Logging failures never interrupt a junction operation.

Mutating actions

Actions marked WRITE may change the filesystem. The TUI asks for confirmation unless dry-run is enabled. Cancelling leaves everything untouched.

sequenceDiagram
    participant U as User
    participant T as TUI
    participant C as Core
    U->>T: Select a WRITE action
    T->>U: Prompt for paths / options
    T->>U: Confirm mutation
    alt Cancelled
        T-->>U: No changes
    else Confirmed
        T->>C: Run operation
        C-->>T: Result object
        T-->>U: Status toast + result table
    end

Non-interactive fallback

If input or output is redirected, the TUI switches to line prompts instead of raw key reads. For automation, prefer the Command-line reference rather than driving the prompts.

Command-line reference

Every headless command goes through the same entry point:

JunctionManager.bat <flags>

You can also call pwsh -NoProfile -File .\JunctionManager.ps1 <flags>.

Read-only commands

CommandDescription
--listList all modules and action IDs
--search <query>Search actions by ID, label, module name or module ID
--scan [root]Scan standard roots, or a custom directory at depth 2
--inspect <path>Inspect one junction and print its status
--export <file> [--csv]Export the current inventory as JSON (default) or CSV
--backupWrite a timestamped JSON snapshot under backups\
--helpShow help

Mutating commands

CommandDescription
--create <path> --target <dir>Create a junction at <path> pointing to <dir>
--retarget <path> --target <dir>Point an existing junction at a new target
--repair <path> [--target <dir>]Recreate a missing junction or repair a stale one
--remove <path>Detach a junction; the target is kept
--clean-staleRemove every Stale-* junction
--clean-orphanedRemove junctions whose target is missing
--clean-emptyRemove junctions whose target is empty
--clean-stale-emptyRemove stale junctions and delete reclaimed empty targets
--restore <file>Recreate missing junctions from an inventory file

Destructive commands require --yes or --dry-run. Without either, they refuse with exit code 2 and leave the filesystem untouched.

Options

OptionEffect
--dry-run, --what-ifPreview changes without writing
--yes, -yConfirm destructive headless actions
--log [path]Enable diagnostic logging; optional custom path
--csvExport CSV instead of JSON
--no-pauseSkip trailing pauses (batch files)
--path <value>Supply a path when a positional path is inconvenient

Exit codes

CodeMeaning
0Success
1Operation failed, inspection found a missing path, or an exception occurred
2Usage error: missing argument, unknown flag, or refused destructive action

Examples

Inspect and scan

JunctionManager.bat --list
JunctionManager.bat --search clean
JunctionManager.bat --scan
JunctionManager.bat --scan "C:\Users\me\AppData\Local\Programs"
JunctionManager.bat --inspect "C:\Users\me\AppData\Local\Programs\App"

Create and manage

JunctionManager.bat --create "C:\Users\me\AppData\Local\Programs\App" --target "D:\Apps\App"
JunctionManager.bat --retarget "C:\Users\me\AppData\Local\Programs\App" --target "D:\Apps\App-2" --yes
JunctionManager.bat --repair "C:\Users\me\AppData\Local\Programs\App" --target "D:\Apps\App"
JunctionManager.bat --remove "C:\Users\me\AppData\Local\Programs\App" --yes

Clean safely

JunctionManager.bat --clean-stale --dry-run
JunctionManager.bat --clean-orphaned --dry-run
JunctionManager.bat --clean-empty --dry-run
JunctionManager.bat --clean-stale-empty --dry-run
JunctionManager.bat --clean-stale-empty --yes --log

Inventory and restore

JunctionManager.bat --export logs\inventory.json
JunctionManager.bat --export logs\inventory.csv --csv
JunctionManager.bat --backup
JunctionManager.bat --restore logs\inventory.json --dry-run
JunctionManager.bat --restore logs\inventory.json --yes

Scripting pattern

# Preview, then apply only if a preview shows work to do.
pwsh -NoProfile -File .\JunctionManager.ps1 --clean-stale --dry-run
if ($LASTEXITCODE -eq 0) {
    pwsh -NoProfile -File .\JunctionManager.ps1 --clean-stale --yes
}

Output and logs

Human-readable output goes to standard output. Fatal usage errors go to standard error. When --log is enabled, the same session writes timestamped INFO, WARN, ERROR and DEBUG lines to logs\windows-junction-manager-YYYY-MM-DD.log.

See Safety and protected paths for the rules every command enforces.

Safety and protected paths

Safety is enforced in the core, not only in the menus. The TUI and the CLI both call the same validation and protection functions.

Protected paths

These paths are never created, retargeted, removed or deleted:

CategoryExamples
Drive rootsC:\, D:\
Windows system%SystemRoot%, %SystemRoot%\System32
Program locations%ProgramFiles%, %ProgramFiles(x86)%
User rootsC:\Users, C:\Users\Public, C:\Users\Default, C:\Documents and Settings
User profile%USERPROFILE% and compatibility names: Application Data, Cookies, Local Settings, My Documents, NetHood, PrintHood, Recent, SendTo, Start Menu, Templates, Desktop, Documents, Downloads
Local app data%LOCALAPPDATA% and Application Data, History, Temporary Internet Files
Roaming app data%APPDATA%
Program data%ProgramData% and Application Data, Desktop, Documents, Start Menu, Templates

Protection uses normalized, case-insensitive equality against the protected set. It does not treat a path as protected merely because the string starts with a protected name.

Validation rules

Before a junction is created, the core checks:

  1. A junction path and target are both supplied.
  2. The junction path is not a drive root.
  3. The junction path is not protected.
  4. Neither path is a UNC network path.
  5. The junction path and target are different.
  6. The junction path is not inside its own target.
  7. The target exists and is not protected.
  8. The junction path does not already exist.
  9. The parent directory of the junction path exists.

Failures are collected and reported together, so a user sees every problem at once.

flowchart TD
    A[Request] --> B{Path and target supplied?}
    B -- No --> X[Reject]
    B -- Yes --> C{Protected, UNC, drive root or nested?}
    C -- Yes --> X
    C -- No --> D{Target exists and is local?}
    D -- No --> X
    D -- Yes --> E{Link path already exists?}
    E -- Yes --> X
    E -- No --> F[Create]

Protected compatibility junctions

Windows keeps compatibility junctions in user profiles and ProgramData. These are exactly the links this tool must never touch. The protected set includes their common names and the user-profile roots, and scanning excludes protected records by default.

Dry-run guarantees

Every mutating operation accepts --dry-run (CLI) or the D toggle (TUI):

OperationDry-run result
CreateReturns a preview result; no link is created
RetargetReturns a preview; the existing link is untouched
RepairReturns a preview; no link is recreated
RemoveReports the link that would be detached; nothing is removed
CleanupReports counts and per-link results; nothing is removed
Empty-target deleteReports the directory; nothing is deleted
Export / backupReports the destination; no file is written
RestoreCounts what would be created or skipped; no link is created

Removal semantics

Removing a junction detaches the reparse point. It does not follow the link and does not delete target contents. The operation uses a non-recursive directory delete, with rmdir as a fallback.

sequenceDiagram
    participant U as User
    participant C as Core
    participant W as Windows
    U->>C: Remove junction
    C->>C: Inspect (exists, is junction, not protected)
    C->>W: Detach reparse point
    W-->>C: Success
    C-->>U: Link removed; target preserved

Empty-target deletion

remove-empty-target and --clean-stale-empty include additional guards. The directory must:

  • exist,
  • not be protected,
  • not be a drive root,
  • not itself be a junction,
  • contain no files,
  • contain no nested reparse points.

If any guard fails, the operation stops with an explanatory error.

Retarget rollback

Retarget removes the old link and creates a new one. If creation fails and the previous target still exists, the core attempts to recreate the original link and reports the failure. This keeps a failed retarget from leaving the application without its junction when recovery is possible.

Restore guards

Restore never overwrites existing paths. A record is skipped when:

  • its link path is protected,
  • its link path already exists,
  • its target directory is missing.

Only missing links with present, unprotected targets are recreated.

Filesystem behavior

The tool does not gate on filesystem type. Targets may live on any local filesystem, and operations are attempted through Windows. If a volume rejects a reparse point, the native error is surfaced and the caller can decide what to do. See Research: junction behavior for the underlying platform notes.

Troubleshooting

pwsh was not found

Symptom: a batch file prints PowerShell 7 (pwsh.exe) was not found in PATH.

Cause: the launchers intentionally use pwsh from PATH and never hard-code an install location.

Fix: install PowerShell 7 with your normal package manager, then open a new terminal so PATH refreshes.

where pwsh

A junction was refused on a volume

Symptom: creation fails with a native error such as Local NTFS volumes are required to complete the operation or Incorrect function.

Cause: the volume that would host the link does not support reparse points. This is a platform limit, not a filesystem-type gate in the tool.

What to do: create the link on a volume that supports reparse points and point it at the target on the other volume. Targets are filesystem-agnostic.

Access denied

Symptom: the operation reports access denied.

Cause: the link path or parent directory requires elevation or different ACLs.

What to do: run the terminal elevated when the location genuinely requires it. Protected paths remain refused even when elevated.

A junction shows Stale-Orphaned

Symptom: inspection reports Stale-Orphaned.

Cause: the target directory no longer exists.

Options:

  • Recreate the target, then inspect again.
  • Retarget the junction to a valid directory.
  • Remove the stale link with --remove <path> --yes or --clean-stale --yes.

A junction shows Stale-Empty

Symptom: the target exists but contains no files.

Options:

  • If the target is genuinely unused, --clean-stale-empty --yes detaches the link and reclaims the empty target when its guards pass.
  • If files are expected, populate the target first; the status becomes Active.

Cause: the new target was rejected, and automatic recovery could not restore the old link because the previous target had already disappeared.

What to do: run --repair <path> --target <valid-dir> to recreate the junction.

Restore skipped everything

Restore skips records when the link path is protected, the link already exists, or the target is missing. Run a preview to see the reason for each record:

JunctionManager.bat --restore logs\inventory.json --dry-run

Logs are empty

Logging is opt-in. Enable it with --log or the L toggle. If the logs folder cannot be written, the core deliberately continues without failing the operation.

Tests do not run

Check that pwsh is available and that suites exist:

tests\RunTests.bat --list
tests\RunTests.bat --all --native

The runner works without Pester by using its bundled native engine. Use --pester only when Pester 5+ is installed.

Still stuck

Include the following when asking for help:

  • the exact command or TUI action,
  • the reported status and reason,
  • the native error text verbatim,
  • whether the path is protected,
  • the relevant log lines with sensitive paths redacted.

Architecture

Windows Junction Manager is a portable PowerShell 7 application with two surfaces over one core:

  • an interactive terminal UI for exploration and guided operations;
  • a headless CLI for scripting and CI.

Both surfaces read the same action catalog and call the same core functions. There is no separate implementation to drift.

Layering

flowchart TD
    B["JunctionManager.bat<br/>PATH pwsh launcher"] --> E["JunctionManager.ps1<br/>root entry point"]
    E --> M["src/menu.ps1<br/>dispatcher and TUI"]
    M --> MF["src/core/manifest.ps1<br/>load order"]
    MF --> V["version.ps1"]
    MF --> P["paths.ps1"]
    MF --> J["junctions.ps1"]
    MF --> O["operations.ps1"]
    MF --> I["inventory.ps1"]
    MF --> K["catalog.ps1"]
    MF --> L["logger.ps1"]
    MF --> U["ui-helpers.ps1"]
    M --> T["Interactive TUI"]
    M --> C["Headless CLI"]
    T --> K
    C --> K
    K --> O
    K --> J
    J --> P
    O --> P
    O --> J
    I --> O
    I --> P
LayerFileResponsibility
LauncherJunctionManager.batConfirm pwsh is on PATH, then invoke the root script
Entry pointJunctionManager.ps1Resolve the repository root and hand off to src/menu.ps1
Presentationsrc/menu.ps1Parse CLI flags, render the TUI, dispatch catalog actions
Catalogsrc/core/catalog.ps1Canonical module/action definitions and search
Coresrc/core/*.ps1Paths, inspection, operations, inventory, logging, UI primitives

The launcher and entry point intentionally contain no product logic. This keeps the application runnable from any folder and testable without a terminal.

Bootstrap and load order

src/core/manifest.ps1 is the single source of module load order. The entry point and the test harness both call Get-WjmCoreModulePaths rather than hard-coding a list.

flowchart LR
    A["menu.ps1"] --> B["manifest.ps1"]
    B --> C["version.ps1"]
    C --> D["paths.ps1"]
    D --> E["junctions.ps1"]
    E --> F["operations.ps1"]
    F --> G["inventory.ps1"]
    G --> H["catalog.ps1"]
    H --> I["logger.ps1"]
    I --> J["ui-helpers.ps1"]

The order matters:

  1. version.ps1 supplies product metadata.
  2. paths.ps1 has no dependency and defines validation primitives.
  3. junctions.ps1 depends on path normalization and protection.
  4. operations.ps1 depends on inspection and validation.
  5. inventory.ps1 depends on operations.
  6. catalog.ps1 is independent of the filesystem and describes the surface.
  7. logger.ps1 and ui-helpers.ps1 are presentation and diagnostics support.

Because the modules are dot-sourced into one scope, adding a module means adding one line to the manifest and nothing else.

Request flow

Read-only scan

sequenceDiagram
    participant U as Caller
    participant M as menu.ps1
    participant J as junctions.ps1
    participant P as paths.ps1
    U->>M: --scan [root]
    M->>P: Get-WjmStandardScanRoots
    P-->>M: existing roots
    M->>J: Get-WjmJunctions roots depth
    loop each root
        J->>J: enumerate children, skip non-junction reparse points
        J->>P: Test-WjmProtectedPath
        J->>J: classify target state
    end
    J-->>M: junction records
    M-->>U: table, status toast, exit code

Discovery never recurses through a reparse point that is not a junction. This avoids traversing symlinks, mount points, or junctions into unrelated volumes.

Mutation

sequenceDiagram
    participant U as Caller
    participant M as menu.ps1
    participant O as operations.ps1
    participant P as paths.ps1
    participant W as Windows
    U->>M: --create PATH --target DIR
    M->>O: New-WjmJunction
    O->>P: Assert-WjmCreatableJunction
    alt invalid
        P-->>O: collected validation errors
        O-->>M: throw with all errors
    else valid
        O->>W: New-Item -ItemType Junction
        alt success
            W-->>O: junction created
        else native failure
            W-->>O: OS error
            O-->>M: throw with native message
        end
        O-->>M: operation result
    end
    M-->>U: result table, exit code

Validation always runs before any filesystem mutation. Native operating-system errors are wrapped with the action and paths, but the original message is preserved.

Result contracts

Core functions return small, stable objects rather than writing to the console. Presentation decides how to render them.

ProducerObjectFields
New-WjmOperationResultOperation resultAction, Success, DryRun, JunctionPath, TargetPath, PreviousTarget, Message, TimestampUtc
Get-WjmJunctionInfoJunction recordJunctionPath, Name, TargetPath, Status, Reason, TargetExists, ContainsFiles, Protected, LinkType, IsJunction, Exists
Clear-WjmStaleJunctionsCleanup resultSuccess, DryRun, Removed, Failed, TargetsRemoved, Results
Export-WjmInventoryExport resultAction, Success, DryRun, Path, Format, Count, GeneratedUtc
Import-WjmInventoryManifestSchema, GeneratedUtc, Path, Count, Junctions
Restore-WjmInventoryRestore resultSuccess, DryRun, Created, Skipped, Failed, Details
Get-WjmJunctionSummarySummaryTotal, Active, Orphaned, Empty, Other, Stale

Keeping these shapes stable is what lets the CLI, TUI, tests, and inventory schema evolve independently.

Dry-run model

Dry-run is a first-class parameter, not a presentation flag. Every mutating core function accepts -DryRun and returns the same result shape with DryRun = $true and a “Would …” message.

flowchart TD
    A[Action requested] --> B{Validate}
    B -- invalid --> X[Throw before mutation]
    B -- valid --> C{DryRun}
    C -- yes --> D[Return preview result]
    C -- no --> E[Attempt native operation]
    E --> F[Return actual result]

The TUI adds a session-level D toggle. The CLI adds --dry-run per command. Because the switch lives in the core, no surface can accidentally skip the check.

CLI exit codes

CodeMeaning
0Success
1Operation failed, inspection found a missing path, or an exception occurred
2Usage error, unknown flag, missing argument, or a refused destructive action

Destructive commands (--retarget, --remove, --clean-*, --restore) require --yes or --dry-run. The refusal happens in the dispatcher before the core is called.

Filesystem-agnostic boundary

The core does not inspect volume type, cluster size, or filesystem name before an operation. It normalizes the path, applies the protection policy, then asks Windows to perform the work.

flowchart LR
    A[Normalized path] --> B{Protected or invalid?}
    B -- yes --> X[Reject with reason]
    B -- no --> C[Attempt native operation]
    C --> D{Native success?}
    D -- yes --> E[Return result]
    D -- no --> F[Surface native error]

This is deliberate. A volume can reject a link for reasons the tool cannot predict, and a guessed filesystem gate would hide the real message. See Research: junction behavior for the platform evidence.

Architectural invariants

  1. One catalog. The TUI, CLI, documentation, and tests read the same definitions.
  2. One load order. No file repeats the module list.
  3. Validation before mutation. Every operation asserts first.
  4. Dry-run is core-level. No surface reimplements it.
  5. Protected paths are never mutated. Enforcement lives in paths.ps1 and is called by operations.
  6. Removal detaches only. The target is never followed or deleted with the link.
  7. Restore never overwrites. Existing paths and protected paths are skipped.
  8. Native behavior wins. Operations are attempted and results are reported, not pre-empted.

Core modules

Every module under src/core is dot-sourced through manifest.ps1. This page is the function-level reference. It is organized in load order.

Module map

ModulePrimary concernKey entry points
manifest.ps1Load orderGet-WjmCoreModulePaths
version.ps1Product metadataGet-WjmProductName, Get-WjmVersion
paths.ps1Normalization, protection, validationGet-WjmJunctionValidation, Assert-WjmCreatableJunction
junctions.ps1Inspection and discoveryGet-WjmJunctionInfo, Get-WjmJunctions
operations.ps1MutationsNew-WjmJunction, Set-WjmJunctionTarget, Clear-WjmStaleJunctions
inventory.ps1Export, import, restoreExport-WjmInventory, Restore-WjmInventory
catalog.ps1Surface definitionGet-WjmCatalog, Search-WjmCatalog
logger.ps1DiagnosticsInitialize-WjmLogger, Write-WjmLog
ui-helpers.ps1Palette and framesGet-WjmPalette, Write-WjmFrame

manifest.ps1

Returns the ordered list of module paths. Callers pass a core directory when they are loading from a different root, as the test harness does.

FunctionPurpose
Get-WjmCoreModulePaths -CoreDir <dir>Return module paths in load order
foreach ($module in (Get-WjmCoreModulePaths -CoreDir $CoreDir)) { . $module }

Adding a module requires exactly one new line here.


version.ps1

Version metadata stays out of the presentation layer so the CLI, TUI, inventory manifest, and tests read one value.

FunctionReturns
Get-WjmProductNameWindows Junction Manager
Get-WjmVersionSemantic version string

The inventory writer stamps both values into JSON exports. Release history lives in CHANGELOG.md.


paths.ps1

Path normalization, the protected-path policy, scan roots, and validation. This module is the safety floor for every operation.

Normalization and classification

FunctionBehavior
ConvertTo-WjmPathExpand environment variables, strip \\?\ and \\?\UNC\ prefixes, convert / to \, remove trailing separators except drive roots, return '' for empty input
Test-WjmDriveRootTrue for X:\
Test-WjmUncPathTrue when the normalized path starts with \\
Test-WjmPathWithinCase-insensitive containment without prefix false positives
Test-WjmEntryExistsTrue when Get-Item resolves the path, including broken junctions

Protection and scan roots

FunctionBehavior
Get-WjmProtectedPathsBuild a case-insensitive set of protected roots and compatibility names
Test-WjmProtectedPathTrue for protected paths and drive roots
Get-WjmStandardScanRootsReturn existing standard roots in discovery order

The protected set is derived from the current environment, not a fixed drive letter:

  • drive roots and %SystemDrive%;
  • %SystemRoot% and %SystemRoot%\System32;
  • %ProgramFiles% and %ProgramFiles(x86)%;
  • C:\Users, C:\Users\Public, C:\Users\Default, C:\Documents and Settings;
  • %USERPROFILE% and its compatibility leaf names;
  • %LOCALAPPDATA% and its compatibility leaf names;
  • %APPDATA%;
  • %ProgramData% and its compatibility leaf names.

Validation

FunctionReturns
Get-WjmTargetValidation -Target <dir>Valid, Target, Errors
Get-WjmJunctionValidation -Path <path> -Target <dir>Valid, Path, Target, Errors
Assert-WjmCreatableJunctionValidation object or throws with all errors joined
Assert-WjmTargetPathNormalized target or throws

Get-WjmJunctionValidation checks, in order:

  1. Both arguments are present.
  2. The link path is not a drive root.
  3. The link path is not protected.
  4. The link path is not UNC.
  5. Link and target differ.
  6. The link is not nested inside its own target.
  7. The target is local, existing, and unprotected.
  8. The link path does not already exist.
  9. The parent directory of the link exists.

Errors accumulate so the caller can show every problem at once.


junctions.ps1

Inspection and discovery. Nothing here mutates the filesystem.

FunctionPurpose
Get-WjmItem -Path <path>Get-Item wrapper that returns $null on failure
Get-WjmJunctionTarget -Path <path>Normalized target for a junction, or ''
Test-WjmTargetHasFiles -Target <dir>True when at least one file exists recursively
Get-WjmJunctionStatus -JunctionPath <path> -TargetPath <dir>Status, reason, TargetExists, ContainsFiles
New-WjmJunctionRecord -Item <item>Build a junction record from a Get-Item result
Get-WjmJunctionInfo -Path <path>Full record for one path, including Missing and Not-A-Junction
Get-WjmJunctions -Roots <dirs> -MaxDepth <n>Recursive discovery with protected filtering
Get-WjmStaleJunctions -Junctions <records>Filter to Stale-*
Get-WjmJunctionSummary -Junctions <records>Aggregate counts

Status classification

stateDiagram-v2
    [*] --> Missing: path does not exist
    [*] --> NotAJunction: path exists, LinkType is not Junction
    [*] --> StaleOrphaned: target missing or unresolved
    [*] --> StaleEmpty: target exists, contains no files
    [*] --> Active: target exists and contains files
    StaleOrphaned --> [*]
    StaleEmpty --> [*]
    Active --> [*]

The status text is part of the public surface and is used in tests and documentation:

StatusReason
ActiveTarget exists and contains files
Stale-OrphanedTarget directory does not exist, or the target could not be resolved
Stale-EmptyTarget exists but contains 0 files
MissingInspected path does not exist
Not-A-JunctionPath exists but LinkType is not Junction

Discovery rules

Get-WjmJunctions walks each root:

  • A directory whose LinkType is Junction becomes a record.
  • Protected records are skipped unless -IncludeProtected is set.
  • Any other reparse point is not descended into, so discovery never crosses a symlink or mount point.
  • Plain directories are walked until MaxDepth is reached.
  • Results are sorted by junction path.

A missing scan root returns an empty list rather than throwing.


operations.ps1

All mutations live here. Every function accepts -DryRun and validates before touching the filesystem.

FunctionBehavior
New-WjmOperationResultConstruct the standard result object
New-WjmJunctionValidate, then New-Item -ItemType Junction
Remove-WjmJunctionInspect, then detach with Directory.Delete(path, $false) and rmdir fallback
Set-WjmJunctionTargetRemove and recreate; restore the previous target on failure when it still exists
Repair-WjmJunctionRecreate a missing junction, retarget a stale one, no-op when healthy
Remove-WjmEmptyTargetDirectoryDelete a target only when empty, unprotected, non-root, and free of nested reparse points
Clear-WjmStaleJunctionsIterate stale records, remove links, optionally reclaim empty targets

Create

flowchart TD
    A[New-WjmJunction] --> B[Assert-WjmCreatableJunction]
    B -- invalid --> X[Throw all errors]
    B -- valid --> C{DryRun}
    C -- yes --> D[Preview result]
    C -- no --> E[New-Item -ItemType Junction]
    E -- native error --> F[Throw with native message]
    E -- success --> G[Result]

Retarget and rollback

sequenceDiagram
    participant C as Caller
    participant O as operations.ps1
    participant W as Windows
    C->>O: Set-WjmJunctionTarget
    O->>O: inspect and validate target
    alt same target
        O-->>C: no-op result
    else new target
        O->>W: remove old link
        O->>W: create link to new target
        alt creation succeeds
            W-->>O: success
            O-->>C: retarget result
        else creation fails
            W-->>O: native error
            O->>W: recreate link to previous target (if still present)
            O-->>C: throw with native error
        end
    end

Removal semantics

Remove-WjmJunction uses a non-recursive delete. This detaches the reparse point and leaves the target and its contents untouched. If the .NET call fails, it retries with rmdir, which also detaches the link.

Empty-target guards

Remove-WjmEmptyTargetDirectory refuses to act when the directory:

  • is protected or a drive root;
  • is itself a junction;
  • contains files;
  • contains nested reparse points.

The checks run before -DryRun returns, so a preview reflects the same decisions as a live run.

Cleanup aggregation

Clear-WjmStaleJunctions returns both per-record results and totals. A failed record increments Failed but does not stop the remaining records. TargetsRemoved counts only reclaimed empty targets.


inventory.ps1

Stable JSON/CSV export, import, backup, and guarded restore.

FunctionBehavior
ConvertTo-WjmInventoryRecordProject a junction record onto the inventory schema
Export-WjmInventoryWrite JSON or CSV, or return a preview when -DryRun
Import-WjmInventoryParse and normalize a JSON inventory or a bare array
Restore-WjmInventoryRecreate only missing, unprotected links whose targets still exist
Backup-WjmInventoryWrite a timestamped JSON snapshot under backups\

JSON schema

{
  "Schema": "wjm.inventory.v1",
  "Product": "Windows Junction Manager",
  "Version": "<version>",
  "ComputerName": "<host>",
  "GeneratedUtc": "<ISO-8601>",
  "Count": 1,
  "Junctions": [
    {
      "JunctionPath": "C:\\path\\link",
      "TargetPath": "D:\\path\\target",
      "Status": "Active",
      "Reason": "Target exists and contains files",
      "Protected": false,
      "TargetExists": true,
      "ContainsFiles": true
    }
  ]
}

The importer accepts the wjm.inventory.v1 object or a bare array of records. It rejects unknown schema families, missing JunctionPath/TargetPath, empty files, and malformed JSON.

Restore decision flow

flowchart TD
    A[Record] --> B{Protected link?}
    B -- yes --> S[Skip: Protected path]
    B -- no --> C{Link already exists?}
    C -- yes --> S2[Skip: Path already exists]
    C -- no --> D{Target exists?}
    D -- no --> S3[Skip: Target missing]
    D -- yes --> E[DryRun?]
    E -- yes --> P[Report would create]
    E -- no --> F[New-WjmJunction]

Restore never overwrites. This makes it safe to run repeatedly against a snapshot.


catalog.ps1

The single source of truth for the product surface. See Action catalog for the full table.

FunctionReturns
Get-WjmCatalogArray of module objects, each with Items
Get-WjmAllActionsFlat list with ModuleId and ModuleName added
Find-WjmAction -ActionId <id>One action or $null, case-insensitive
Search-WjmCatalog -Query <text>Matching module/item pairs
Get-WjmCatalogTotalNumber of actions

Search is a case-insensitive substring match over action ID, label, module name, and module ID. An empty query returns every action.


logger.ps1

Opt-in diagnostics. A logging failure never interrupts a junction operation.

FunctionBehavior
Initialize-WjmLoggerCreate the log directory, prune old logs, write SESSION START, return the log path
Write-WjmLog -Message <text> -Level <INFO|WARN|ERROR|DEBUG>Append a timestamped line when enabled
Close-WjmLogger -ExitCode <n>Write SESSION END and disable logging
Test-WjmLogEnabledCurrent enabled state
Get-WjmLogPathActive log file path

Default log name: windows-junction-manager-YYYY-MM-DD.log. Retention defaults to 30 days and applies only to the default log directory.


ui-helpers.ps1

ANSI palette, width and truncation helpers, header/footer builders, and frame rendering. Rendering degrades to plain text when output is redirected or NO_COLOR is set.

FunctionPurpose
Initialize-WjmUiBuild the palette or a no-color equivalent
Get-WjmPaletteLazy-initialize and return the palette
Format-WjmTruncateClip text with an ellipsis
Get-WjmUiWidthClamp the frame width to the console
Build-WjmHeaderBlockHeader with brand, subtitle, and status pills
Build-WjmFooterBlockRule, toast, and hint line
Set-WjmStatus / Get-WjmStatusSession toast state
Clear-WjmScreen / Write-WjmFrameFull or in-place frame output

The palette is shared with the test runner so both interfaces look consistent. Write-WjmFrame and Clear-WjmScreen consult $script:WjmCanReadKey, which the caller sets when a real console is available.

Action catalog

src/core/catalog.ps1 defines 5 modules and 24 actions. It is the only place those definitions live. The TUI, the headless CLI, the documentation, and the automated tests all read from it.

Why a catalog

Without a single definition, it is easy for the menu to offer an action the CLI cannot run, or for documentation to describe an action that no longer exists. The catalog prevents that drift:

flowchart TD
    K["catalog.ps1<br/>5 modules / 24 actions"]
    K --> T["src/menu.ps1<br/>TUI menus and hotkeys"]
    K --> C["src/menu.ps1<br/>CLI --list / --search"]
    K --> D["Documentation<br/>module and action tables"]
    K --> X["tests/suites/02_Catalog<br/>counts, IDs, fields"]
    K --> H["tests/suites/01_SyntaxAndDocs<br/>README/doc count alignment"]
    T --> E["Invoke-WjmAction"]
    C --> E

Data model

Each module is an ordered hashtable with these fields:

FieldTypeMeaning
MenuKeystringTop-level TUI hotkey (1–5)
ModuleIdstringStable machine identifier (scan, manage, clean, backup, settings)
NamestringDisplay name
DescriptionstringOne-line purpose shown in the TUI
OptionalboolReserved for future optional modules; currently $false
ItemsarrayOrdered actions

Each action item has:

FieldTypeMeaning
IdstringStable action identifier, unique across the catalog
MenuKeystringHotkey inside the module (1–6)
LabelstringDisplay label
ActionstringDispatcher key used by Invoke-WjmAction
NeedsInputboolWhether the action prompts for a path or file
MutatesboolWhether the action can change the filesystem

Get-WjmAllActions flattens the catalog and adds ModuleId and ModuleName to each item. Find-WjmAction resolves by ID. Search-WjmCatalog returns module/item pairs.

Modules and actions

1. Scan & Inspect (scan)

Discover, inspect, and classify junctions. All read-only.

KeyAction IDLabelInputMutates
1scan-standardScan Standard LocationsNoNo
2scan-pathScan a Custom DirectoryYesNo
3inspectInspect One JunctionYesNo
4stale-reportStale Junction ReportNoNo
5summaryInventory Summary DashboardNoNo
6verifyVerify Junction HealthNoNo

2. Create & Manage (manage)

Create, retarget, repair, and remove junctions. All mutating.

KeyAction IDLabelInputMutates
1createCreate a New JunctionYesYes
2retargetRetarget an Existing JunctionYesYes
3repairRepair a JunctionYesYes
4removeRemove a JunctionYesYes
5remove-empty-targetDelete an Empty Target DirectoryYesYes

3. Clean & Repair (clean)

Remove stale links and optionally reclaim empty targets. All mutating.

KeyAction IDLabelInputMutates
1clean-staleClean All Stale JunctionsNoYes
2clean-orphanedClean Orphaned (Missing Target)NoYes
3clean-emptyClean Empty-Target JunctionsNoYes
4clean-stale-emptyClean Stale + Empty TargetsNoYes

4. Backup & Export (backup)

Export inventory, back up, and restore links. Only restore mutates.

KeyAction IDLabelInputMutates
1export-jsonExport Inventory to JSONYesNo
2export-csvExport Inventory to CSVYesNo
3backupBack Up Inventory SnapshotNoNo
4import-previewPreview an Inventory FileYesNo
5restoreRestore Junctions from BackupYesYes

5. Settings & Safety (settings)

Inspect the protection policy, scan roots, logs, and version. All read-only.

KeyAction IDLabelInputMutates
1list-protectedShow Protected PathsNoNo
2show-rootsShow Standard Scan RootsNoNo
3open-logsOpen Logs FolderNoNo
4aboutAbout & VersionNoNo

Catalog invariants

These are enforced by 02_Catalog.Tests.ps1:

  1. Exactly 5 modules.
  2. Exactly 24 actions.
  3. Module IDs are stable and unique.
  4. Action IDs are stable and unique across all modules.
  5. Every action has Id, MenuKey, Label, Action, NeedsInput, and Mutates.
  6. Every action is reachable from its module menu key.
  7. Mutates is $true for every operation that can change the filesystem and $false for every read-only action.
  8. README.md, README.txt, and the documentation state the same counts.

The counts also appear literally in the documentation so readers can verify a build at a glance.

Search semantics

Search-WjmCatalog -Query <text> performs a case-insensitive substring match against:

  • the action ID;
  • the action label;
  • the module name;
  • the module ID.

An empty or whitespace query returns every action. --search clean therefore returns the four cleanup actions, and --search backup returns the module and its actions.

Adding or removing an action

Changing the surface is a coordinated change. Do all of these together:

  1. Add or remove the item in Get-WjmCatalog.
  2. Add or remove the matching branch in Invoke-WjmAction in src/menu.ps1.
  3. Add a headless flag and dispatch branch if the action should be scriptable.
  4. Update the module/action tables in this page and the user documentation.
  5. Update the literal counts in README.md and README.txt if the total changes.
  6. Update 02_Catalog.Tests.ps1 and 01_SyntaxAndDocs.Tests.ps1.
  7. Run the full suite.

The catalog is intentionally data-only. Keep behavior in src/menu.ps1 or the core modules, not in the hashtables.

  • Architecture — how the catalog sits between surfaces and core.
  • Core modules — catalog function reference.
  • Testing — how catalog invariants are verified.

Testing

The project ships a modular test runner with automatic suite discovery. The same *.Tests.ps1 suites run under Pester 5 when it is installed and under a bundled zero-dependency native engine otherwise.

Runner architecture

flowchart TD
    A["tests/RunTests.bat<br/>PATH pwsh launcher"] --> B["tests/Run-Tests.ps1"]
    B --> C["Discover tests/suites/*.Tests.ps1"]
    B --> D{Engine}
    D -- "Pester 5 installed or --pester" --> E["Invoke-Pester per suite"]
    D -- "no Pester or --native" --> F["tests/helpers/TestHarness.ps1"]
    F --> G["native Describe / It / Should shim"]
    E --> H["Per-suite results"]
    G --> H
    H --> I["Totals, status, exit code"]

The runner has two modes:

  • TUI when a real console is available and no CLI flag is passed.
  • Headless for --list, --all, --suite, and CI.

Running the suite

tests\RunTests.bat
tests\RunTests.bat --list
tests\RunTests.bat --all
tests\RunTests.bat --suite catalog,paths
tests\RunTests.bat --suite 01,05 --verbose
tests\RunTests.bat --all --pester
tests\RunTests.bat --all --native
tests\RunTests.bat --help
FlagEffect
--listList every discovered suite with its number, slug, and title
--allRun every suite
--suite <names>Run suites by number, slug, or title keyword; comma- or semicolon-separated
--pesterForce Pester 5; fail if it is not installed
--nativeForce the bundled engine
--verboseShow per-case timings
--no-pauseSkip the return-to-menu pause in the TUI

The runner exits 0 when every case passes and 1 when any case fails.

TUI keys

KeyAction
↑ / ↓Move the selection
EnterRun the selected suite
1–9, 0Jump to a suite by number
ARun all suites
PToggle Pester 5 / native engine (when Pester is available)
VToggle verbose timings
Q / EscQuit

Suite inventory

SuiteSlugFocus
01_SyntaxAndDocs01_syntaxanddocsParses every project .ps1; entry points, launcher hygiene, documentation set, catalog-count alignment
02_Catalog02_catalogFive modules, twenty-four actions, unique IDs, required fields, search, menu reachability
03_Paths03_pathsNormalization, drive roots, protected paths, scan roots, containment, validation
04_Junctions04_junctionsMissing/not-a-junction/active/orphaned/empty classification, discovery, summary, stale filter
05_Operations05_operationsCreate, retarget rollback, repair, remove, empty-target deletion, dry-run, cleanup
06_Inventory06_inventoryJSON/CSV export, empty CSV, dry-run export, round-trip import, restore guards, backup
07_Cli07_cliHelp, list, search, inspect, create/retarget/remove, dry-run cleanup, usage errors, destructive refusal
08_CrossVolume08_crossvolumeAlternate-volume targets, native results, alternate-volume link attempts, separator normalization

Engine selection

flowchart TD
    A[Start] --> B{--pester?}
    B -- yes --> C{Pester 5 available?}
    C -- no --> X[Error with install hint]
    C -- yes --> P[Pester 5]
    B -- no --> D{--native?}
    D -- yes --> N[Native engine]
    D -- no --> E{Pester 5 installed?}
    E -- yes --> P
    E -- no --> N

The native engine is not a mock of the product. It is a small test harness that implements the subset of Pester the suites use:

  • BeforeAll, BeforeEach, AfterEach;
  • Describe, It;
  • Should with Be, BeTrue, BeFalse, BeNullOrEmpty, BeGreaterOrEqual, BeLessOrEqual, Match, Contain, BeIn, Throw, and -Not.

If a suite uses a Pester feature outside this subset, it will pass under Pester 5 and fail under the native engine. Keep suites inside the shared subset so both engines behave identically.

Test harness API

tests/helpers/TestHarness.ps1 exposes:

FunctionPurpose
Get-WjmTestRepoRootResolve the repository root from tests/helpers
Get-WjmTestCoreModulePathsRead src/core/manifest.ps1 and return the product’s load order
Invoke-WjmNativeSuiteFileRun one suite with the native shim and return pass/fail counts

The native shim removes any loaded Pester module first, so an older Windows PowerShell Pester cannot hijack the shim when pwsh starts without a clean module path.

Junction test kit

tests/helpers/JunctionTestKit.ps1 provides capability-based fixtures. It follows the same rule as the product: do not gate on filesystem type.

FunctionPurpose
New-WjmTestWorkspaceCreate a temp workspace with target, target2, link, and link2
Get-WjmTestAlternateVolumeRootReturn a second ready fixed volume, or ''
New-WjmTestFileWrite a fixture file, creating parents
New-WjmTestJunctionTry New-Item -ItemType Junction, then mklink /J for broken-target cases
Remove-WjmTestJunctionDetach a link non-recursively, then fall back to rmdir
Remove-WjmTestWorkspaceDetach links first, then remove the workspace tree

Design rules

  1. Attempt, then inspect. A test performs the operation and asserts on the native result instead of skipping because a volume is “not NTFS”.
  2. Links live where creation is most likely to succeed. Workspaces use the current user’s temp directory.
  3. Targets may live elsewhere. When a second fixed volume exists, the kit creates a cross-volume target. If the volume rejects directory creation, the alternate paths are left empty rather than faked.
  4. Cleanup never follows a reparse point. Links are detached before the workspace tree is removed.

Broken junctions

New-Item -ItemType Junction refuses to create a link to a missing target. Broken-junction coverage therefore uses cmd.exe /c mklink /J, which can create the link anyway. This is a testing concern only; the product still surfaces whatever Windows reports.

Writing a suite

  1. Add tests/suites/NN_Name.Tests.ps1.
  2. Start with #Requires -Version 7.0.
  3. In BeforeAll, resolve the repo root, load TestHarness.ps1 and JunctionTestKit.ps1, then dot-source every core module via Get-WjmTestCoreModulePaths.
  4. Use Describe and It. Use BeforeEach/AfterEach for fixtures and cleanup.
  5. Use junction fixtures for filesystem cases and plain temp files where a junction is not required.
  6. Assert behavior and result fields, not console formatting.
  7. Run under both engines when possible:
tests\RunTests.bat --suite NN --native
tests\RunTests.bat --suite NN --pester

The runner auto-discovers new files; no registration is required.

Continuous integration

The test workflow runs on Windows with PowerShell 7 and exercises both engines:

  • checkout;
  • install Pester 5;
  • run tests\Run-Tests.ps1 --all --native --no-pause;
  • run tests\Run-Tests.ps1 --all --pester --no-pause.

Running both engines keeps the native shim in sync with the Pester suites. The cross-volume suite is written to pass when only one volume exists: it attempts the operation and asserts on the observed native result.

Troubleshooting

SymptomCauseFix
Pester 5+ is not installed--pester was forcedInstall Pester 5 or use --native
A suite passes in Pester but fails nativelyThe suite uses a Pester feature outside the shim subsetRewrite the assertion using the supported set
Junction tests fail with access deniedThe temp location or parent requires different ACLsRun the session where the user can write the temp tree
Cross-volume case is skipped-lookingNo second fixed volume existsExpected; the test asserts on the native outcome, not a skip

Contributing

This page describes how to make a change that stays consistent with the project’s structure, safety rules, and test expectations.

Contribution principles

PrincipleWhat it means in practice
Safety firstNever weaken the protected-path policy or add a mutation path that bypasses validation
One catalogDo not hard-code module or action lists outside src/core/catalog.ps1
Native behavior winsDo not add a filesystem-type gate; attempt the operation and surface the result
Dry-run is core-levelEvery new mutating function accepts -DryRun and validates before acting
PortableNo installer, no hard-coded tool paths, no hidden elevation, no network dependency
Local verificationChanges are verified locally with the test runner before they are considered complete

Prerequisites

  • Windows 11
  • PowerShell 7.x (pwsh) available on PATH
  • Optional: Pester 5 for the Pester engine, though the bundled native engine is sufficient

No package restore or build step is required. The tool is dot-sourced PowerShell.

Repository layout

JunctionManager.ps1        Root entry point
JunctionManager.bat        PATH-pwsh launcher
src/
  menu.ps1                 CLI dispatcher and interactive TUI
  core/                    Dot-sourced core modules
tests/
  Run-Tests.ps1            Modular test runner
  RunTests.bat             PATH-pwsh test launcher
  helpers/                 Harness and junction fixtures
  suites/                  Auto-discovered *.Tests.ps1 suites
docs/                      mdBook documentation site
book.toml                  mdBook configuration

Coding conventions

  • Target PowerShell 7 with #Requires -Version 7.0.
  • Use Set-StrictMode -Version Latest and $ErrorActionPreference = 'Stop' at entry points.
  • Name product functions with the Wjm noun prefix (Get-WjmJunctionInfo, New-WjmJunction).
  • Return structured objects; leave rendering to src/menu.ps1.
  • Wrap native errors with the action and paths while preserving the original message.
  • Prefer -LiteralPath for filesystem cmdlets.
  • Do not introduce a filesystem-type check. Validate the path, then attempt the operation.
  • Keep modules independent of console rendering. Only ui-helpers.ps1 and menu.ps1 should emit UI.
  • When adding a module, add it to src/core/manifest.ps1; do not repeat the list anywhere else.

Add an action end to end

Use the Action catalog as the contract. A complete change touches these places together:

  1. Catalog — add the module/item entry in src/core/catalog.ps1.
  2. TUI dispatch — add the branch in Invoke-WjmAction in src/menu.ps1.
  3. CLI dispatch — add the flag parser and Invoke-WjmCliMode branch if it should be scriptable.
  4. Core — add or reuse a core function. If it mutates, accept -DryRun and validate first.
  5. Tests — add a case to the relevant suite and update 02_Catalog.Tests.ps1.
  6. Documentation — update this developer guide and the user-facing reference.
  7. Counts — if the total changes, update the literal counts in README.md, README.txt, and the documentation.
flowchart LR
    A[Catalog entry] --> B[TUI handler]
    A --> C[CLI flag and handler]
    B --> D[Core function]
    C --> D
    D --> E[Tests]
    A --> F[Developer docs]
    A --> G[User docs]
    A --> H[Count references]

Removing an action is the reverse: remove the catalog entry, handlers, tests, and documentation, then update the counts.

Safety review checklist

Before considering a change complete, confirm:

  • Protected paths are still refused for create, retarget, remove, delete, and restore.
  • Drive roots and UNC paths are still rejected where required.
  • A link can never be nested inside its own target.
  • Removal detaches the link only and never follows the target.
  • Empty-target deletion still refuses files, junctions, and nested reparse points.
  • Restore still skips protected, existing, and target-missing records.
  • Every new mutation accepts -DryRun and returns a preview before touching disk.
  • Native errors are surfaced, not replaced by a guessed filesystem check.
  • No credential, cookie, webhook, or environment secret is written to a tracked file.

Documentation requirements

Tracked documentation follows the project’s documentation standards:

  • user material under docs/user/;
  • architecture and extension material under docs/developer/;
  • shared platform research under docs/developer/research/.

Each page should be GFM-compliant, use tables and Mermaid diagrams where they help, use ISO dates, and link to real references. Do not include local paths, usernames, or local-only setup. Keep release history in CHANGELOG.md rather than scattering version claims across the docs.

When you add a page, add it to docs/SUMMARY.md so mdBook includes it.

Verification

Run the full suite headlessly:

tests\RunTests.bat --all

Run a targeted suite while iterating:

tests\RunTests.bat --suite catalog
tests\RunTests.bat --suite paths

Run under both engines when Pester 5 is available:

tests\RunTests.bat --all --native
tests\RunTests.bat --all --pester

Validate the documentation site:

mdbook build

The suite itself parses every project .ps1 file, checks the entry points and documentation set, verifies catalog counts, and exercises the filesystem behavior. A change is not complete until the relevant suites pass.

Review checklist

AreaQuestion
ScopeDoes the change do one coherent thing?
SafetyCould it mutate a protected path or the wrong filesystem object?
ConsistencyDid the catalog, CLI, TUI, tests, and docs move together?
PortabilityDid any hard-coded install path, username, or machine-specific value slip in?
SecretsIs any sensitive value present in a tracked file or log?
VerificationDid the full suite pass, and the docs build if pages changed?

Research: junction behavior

This page records the platform behavior that shapes the product. It is shared research, not a user guide. It explains why the manager attempts operations and reports native results instead of guessing from a volume label.

Last reviewed: 2026-12-04.

Scope

The questions this research answers:

  1. What is a junction at the filesystem level?
  2. Which volumes can host a junction link, and which can host a target?
  3. How do broken junctions behave when inspected and removed?
  4. Which PowerShell and .NET calls are safe for creation, inspection, and detachment?
  5. Why does the product avoid a filesystem-type gate?

What a junction is

A junction is a directory reparse point. The directory entry carries a reparse tag and a small data buffer. When the I/O manager resolves the path, it reads the buffer and redirects to the stored target path.

flowchart LR
    A["Path: C:\\link"] --> B["Directory entry<br/>FILE_ATTRIBUTE_REPARSE_POINT"]
    B --> C["Reparse tag<br/>IO_REPARSE_TAG_MOUNT_POINT"]
    C --> D["Reparse data<br/>substitute name + print name"]
    D --> E["Target: D:\\data"]

Junctions and volume mount points share the IO_REPARSE_TAG_MOUNT_POINT tag (0xA0000003). A junction stores a directory path; a mount point maps a volume. A symbolic link uses IO_REPARSE_TAG_SYMLINK (0xA000000C) and can target files or directories, including remote UNC paths.

AspectJunctionDirectory symbolic linkVolume mount point
Reparse tagIO_REPARSE_TAG_MOUNT_POINTIO_REPARSE_TAG_SYMLINKIO_REPARSE_TAG_MOUNT_POINT
Target kindLocal directory pathLocal or remote pathVolume
Remote targetNoYes (UNC)No
Creation privilegeNo symbolic-link privilege requiredSymbolic-link privilege or Developer ModeTypically administrative
Common creatormklink /J, New-Item -ItemType Junctionmklink /D, New-Item -ItemType SymbolicLinkmountvol, disk management

The product manages junctions only. A path whose LinkType is not Junction is reported as Not-A-Junction and is never modified.

Filesystem support

Volume roleRequirementEvidence
Host of the junction linkMust support reparse pointsNTFS and ReFS support reparse points; FAT32 and exFAT do not
Host of the target directoryAny local filesystem the path can reachThe reparse buffer stores a path string; resolution happens through the I/O manager

The important separation is link volume versus target volume. A target on a filesystem without reparse-point support is still a valid target. Only the link’s own volume must support the reparse point.

flowchart LR
    A["NTFS system volume<br/>junction link"] -->|reparse redirect| B["FAT32 data volume<br/>target directory"]
    C["FAT32 volume<br/>cannot host link"] -.->|native rejection| D["Operation fails"]

Observed behavior

The following were observed on Windows 11 with PowerShell 7 while building this project.

ScenarioCallObserved result
Link on an NTFS system volume targeting a directory on a FAT32 data volumeNew-Item -ItemType JunctionSucceeds; the link resolves to the target
Link path placed directly on the FAT32 data volumeNew-Item -ItemType JunctionFails; Windows returns a native error such as “Incorrect function” or an NTFS-required message
Target directory missingGet-Item on the linkReturns the link entry with LinkType = 'Junction'
Target directory missingNew-Item -ItemType JunctionFails because the target must exist
Target directory missingcmd /c mklink /JCreates a junction whose target is absent
Existing junction[System.IO.Directory]::Delete(path, $false)Detaches the link; target and contents remain
Junction with a missing target[System.IO.Directory]::Delete(path, $false)Detaches the link successfully

Exact error text varies by API, volume, and path. The product does not match on error strings; it surfaces the message unchanged.

API behavior

Inspection

Get-Item exposes reparse metadata through LinkType and Target:

$item = Get-Item -LiteralPath $Path -Force
$item.LinkType   # 'Junction'
$item.Target     # target path, or empty for some broken cases
$item.Attributes # includes ReparsePoint

A broken junction still returns an item, so stale links remain visible, inspectable, and removable. This is why the manager can report Stale-Orphaned and still act on the link.

Creation

New-Item -ItemType Junction is convenient but validates that the target exists. For broken-link fixtures and edge cases, mklink /J can create a junction to a missing target.

mklink /J requires cmd.exe, so the product’s normal creation path uses New-Item. The test kit falls back to mklink only where a broken link is required.

Detachment

[System.IO.Directory]::Delete($Path, $false)

The second argument is recursive: false. This deletes the reparse point itself. Passing $true is dangerous for links because it can traverse into the target and delete its contents. The product never uses a recursive delete on a junction path.

If the .NET call fails, the core retries with cmd /c rmdir "<path>", which also detaches the link rather than following it.

Target emptiness

Test-WjmTargetHasFiles walks the target recursively and stops at the first file. This is a content check, not a filesystem-type check. An empty directory is Stale-Empty regardless of the volume it lives on.

Why the product does not gate on filesystem type

A volume label is a poor predictor of whether a specific operation will succeed:

  • the link and target can live on different volumes;
  • a volume may support reparse points but reject a specific path due to ACLs, path length, or a filter driver;
  • the exact native error is more useful than a guessed “not supported” message;
  • new Windows builds and storage drivers change behavior over time.

The design therefore validates what it can know locally (path shape, protection, existence, containment) and then attempts the operation. The native result is the source of truth.

flowchart TD
    A[Request] --> B[Validate path shape, protection, existence]
    B -- invalid --> X[Reject with reason]
    B -- valid --> C[Attempt native operation]
    C --> D{Native result}
    D -- success --> E[Report success]
    D -- failure --> F[Surface native error]

Design consequences

DecisionReason
Status comes from target existence and content, not volume typeThe link and target may live on different filesystems
Create, retarget, and repair attempt the native callOnly Windows knows whether the path is accepted
Removal uses non-recursive deleteA recursive delete could follow the link into the target
Inspection uses the reparse entry, not the targetBroken links must remain visible and removable
Restore checks target existence and protection, not volume typeTargets may live anywhere local
Test fixtures attempt and assert on native resultsAvoids false skips and mirrors production behavior

Canonical references

Open questions

  • How do specific filter drivers and cloud-sync providers affect junction resolution for directories they manage?
  • Do any supported Windows configurations allow a junction link on a non-NTFS volume through a third-party filesystem driver?
  • How should the tool report a link whose reparse data is readable but whose target path is malformed?

These are tracked as research questions, not current behavior. The product continues to surface native results until a reliable, documented rule exists.