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
| Area | Capability |
|---|---|
| Discovery | Scan standard locations or any custom directory, inspect one junction, summarize health |
| Lifecycle | Create, retarget with rollback, repair and remove junctions |
| Cleanup | Remove orphaned links, empty-target links, or both, with optional empty-target reclamation |
| Inventory | JSON/CSV export, timestamped backup snapshots, import preview and guarded restore |
| Safety | Protected-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
- New to the tool? Start with Getting started.
- Prefer the keyboard? See the Interactive TUI.
- Automating a workflow? Use the Command-line reference.
- Concerned about safety? Read Safety and protected paths.
- Extending or testing the tool? Read the Architecture and Core modules guides.
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
| Requirement | Notes |
|---|---|
| Windows 11 | Junctions are a Windows reparse-point feature |
| PowerShell 7.x | pwsh must be on PATH for the batch launchers |
| Local filesystem | Junction 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
- Run
JunctionManager.bat --listto confirm the catalog loads. You should see 5 modules and 24 actions. - Run
JunctionManager.bat --scanto discover junctions in the standard application locations. - Press
Din the TUI, or pass--dry-runon the CLI, before trying a mutating action. - 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
| Artifact | Location |
|---|---|
| Diagnostic logs | logs\windows-junction-manager-YYYY-MM-DD.log when logging is enabled |
| Backup snapshots | backups\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
- Learn the keyboard workflow in Interactive TUI.
- Automate with the Command-line reference.
- Read Safety and protected paths before cleaning anything.
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
| Key | Main menu | Module menu |
|---|---|---|
↑ / ↓ | Move between modules | Move between actions |
k / j | Vim-style up/down | Vim-style up/down |
Home / End | First / last module | First / last action |
Enter | Open module | Run action |
1–5 | Jump to module | Jump to action |
/ | Open live search | Open live search |
D | Toggle dry-run | Toggle dry-run |
L | Toggle diagnostic logging | Toggle diagnostic logging |
B / Esc | Quit or go back | Go back |
Q | Quit | Quit |
Header pills
| Pill | Meaning |
|---|---|
PS 7.x | PowerShell major/minor version |
ADMIN | Current session is elevated |
STANDARD | Current session is not elevated |
DRY-RUN | Mutating actions preview only |
LOG | Diagnostic logging is active |
Live search
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
| Command | Description |
|---|---|
--list | List 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 |
--backup | Write a timestamped JSON snapshot under backups\ |
--help | Show help |
Mutating commands
| Command | Description |
|---|---|
--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-stale | Remove every Stale-* junction |
--clean-orphaned | Remove junctions whose target is missing |
--clean-empty | Remove junctions whose target is empty |
--clean-stale-empty | Remove 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
| Option | Effect |
|---|---|
--dry-run, --what-if | Preview changes without writing |
--yes, -y | Confirm destructive headless actions |
--log [path] | Enable diagnostic logging; optional custom path |
--csv | Export CSV instead of JSON |
--no-pause | Skip trailing pauses (batch files) |
--path <value> | Supply a path when a positional path is inconvenient |
Exit codes
| Code | Meaning |
|---|---|
0 | Success |
1 | Operation failed, inspection found a missing path, or an exception occurred |
2 | Usage 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:
| Category | Examples |
|---|---|
| Drive roots | C:\, D:\ |
| Windows system | %SystemRoot%, %SystemRoot%\System32 |
| Program locations | %ProgramFiles%, %ProgramFiles(x86)% |
| User roots | C:\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:
- A junction path and target are both supplied.
- The junction path is not a drive root.
- The junction path is not protected.
- Neither path is a UNC network path.
- The junction path and target are different.
- The junction path is not inside its own target.
- The target exists and is not protected.
- The junction path does not already exist.
- 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):
| Operation | Dry-run result |
|---|---|
| Create | Returns a preview result; no link is created |
| Retarget | Returns a preview; the existing link is untouched |
| Repair | Returns a preview; no link is recreated |
| Remove | Reports the link that would be detached; nothing is removed |
| Cleanup | Reports counts and per-link results; nothing is removed |
| Empty-target delete | Reports the directory; nothing is deleted |
| Export / backup | Reports the destination; no file is written |
| Restore | Counts 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> --yesor--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 --yesdetaches the link and reclaims the empty target when its guards pass. - If files are expected, populate the target first; the status becomes
Active.
Retarget failed and the link is missing
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
| Layer | File | Responsibility |
|---|---|---|
| Launcher | JunctionManager.bat | Confirm pwsh is on PATH, then invoke the root script |
| Entry point | JunctionManager.ps1 | Resolve the repository root and hand off to src/menu.ps1 |
| Presentation | src/menu.ps1 | Parse CLI flags, render the TUI, dispatch catalog actions |
| Catalog | src/core/catalog.ps1 | Canonical module/action definitions and search |
| Core | src/core/*.ps1 | Paths, 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:
version.ps1supplies product metadata.paths.ps1has no dependency and defines validation primitives.junctions.ps1depends on path normalization and protection.operations.ps1depends on inspection and validation.inventory.ps1depends on operations.catalog.ps1is independent of the filesystem and describes the surface.logger.ps1andui-helpers.ps1are 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.
| Producer | Object | Fields |
|---|---|---|
New-WjmOperationResult | Operation result | Action, Success, DryRun, JunctionPath, TargetPath, PreviousTarget, Message, TimestampUtc |
Get-WjmJunctionInfo | Junction record | JunctionPath, Name, TargetPath, Status, Reason, TargetExists, ContainsFiles, Protected, LinkType, IsJunction, Exists |
Clear-WjmStaleJunctions | Cleanup result | Success, DryRun, Removed, Failed, TargetsRemoved, Results |
Export-WjmInventory | Export result | Action, Success, DryRun, Path, Format, Count, GeneratedUtc |
Import-WjmInventory | Manifest | Schema, GeneratedUtc, Path, Count, Junctions |
Restore-WjmInventory | Restore result | Success, DryRun, Created, Skipped, Failed, Details |
Get-WjmJunctionSummary | Summary | Total, 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
| Code | Meaning |
|---|---|
0 | Success |
1 | Operation failed, inspection found a missing path, or an exception occurred |
2 | Usage 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
- One catalog. The TUI, CLI, documentation, and tests read the same definitions.
- One load order. No file repeats the module list.
- Validation before mutation. Every operation asserts first.
- Dry-run is core-level. No surface reimplements it.
- Protected paths are never mutated. Enforcement lives in
paths.ps1and is called by operations. - Removal detaches only. The target is never followed or deleted with the link.
- Restore never overwrites. Existing paths and protected paths are skipped.
- Native behavior wins. Operations are attempted and results are reported, not pre-empted.
Related documentation
- Core modules — function-level reference.
- Action catalog — the module/action data model.
- Testing — suites, harness, and CI.
- Safety and protected paths — user-facing policy.
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
| Module | Primary concern | Key entry points |
|---|---|---|
manifest.ps1 | Load order | Get-WjmCoreModulePaths |
version.ps1 | Product metadata | Get-WjmProductName, Get-WjmVersion |
paths.ps1 | Normalization, protection, validation | Get-WjmJunctionValidation, Assert-WjmCreatableJunction |
junctions.ps1 | Inspection and discovery | Get-WjmJunctionInfo, Get-WjmJunctions |
operations.ps1 | Mutations | New-WjmJunction, Set-WjmJunctionTarget, Clear-WjmStaleJunctions |
inventory.ps1 | Export, import, restore | Export-WjmInventory, Restore-WjmInventory |
catalog.ps1 | Surface definition | Get-WjmCatalog, Search-WjmCatalog |
logger.ps1 | Diagnostics | Initialize-WjmLogger, Write-WjmLog |
ui-helpers.ps1 | Palette and frames | Get-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.
| Function | Purpose |
|---|---|
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.
| Function | Returns |
|---|---|
Get-WjmProductName | Windows Junction Manager |
Get-WjmVersion | Semantic 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
| Function | Behavior |
|---|---|
ConvertTo-WjmPath | Expand environment variables, strip \\?\ and \\?\UNC\ prefixes, convert / to \, remove trailing separators except drive roots, return '' for empty input |
Test-WjmDriveRoot | True for X:\ |
Test-WjmUncPath | True when the normalized path starts with \\ |
Test-WjmPathWithin | Case-insensitive containment without prefix false positives |
Test-WjmEntryExists | True when Get-Item resolves the path, including broken junctions |
Protection and scan roots
| Function | Behavior |
|---|---|
Get-WjmProtectedPaths | Build a case-insensitive set of protected roots and compatibility names |
Test-WjmProtectedPath | True for protected paths and drive roots |
Get-WjmStandardScanRoots | Return 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
| Function | Returns |
|---|---|
Get-WjmTargetValidation -Target <dir> | Valid, Target, Errors |
Get-WjmJunctionValidation -Path <path> -Target <dir> | Valid, Path, Target, Errors |
Assert-WjmCreatableJunction | Validation object or throws with all errors joined |
Assert-WjmTargetPath | Normalized target or throws |
Get-WjmJunctionValidation checks, in order:
- Both arguments are present.
- The link path is not a drive root.
- The link path is not protected.
- The link path is not UNC.
- Link and target differ.
- The link is not nested inside its own target.
- The target is local, existing, and unprotected.
- The link path does not already exist.
- 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.
| Function | Purpose |
|---|---|
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:
| Status | Reason |
|---|---|
Active | Target exists and contains files |
Stale-Orphaned | Target directory does not exist, or the target could not be resolved |
Stale-Empty | Target exists but contains 0 files |
Missing | Inspected path does not exist |
Not-A-Junction | Path exists but LinkType is not Junction |
Discovery rules
Get-WjmJunctions walks each root:
- A directory whose
LinkTypeisJunctionbecomes a record. - Protected records are skipped unless
-IncludeProtectedis set. - Any other reparse point is not descended into, so discovery never crosses a symlink or mount point.
- Plain directories are walked until
MaxDepthis 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.
| Function | Behavior |
|---|---|
New-WjmOperationResult | Construct the standard result object |
New-WjmJunction | Validate, then New-Item -ItemType Junction |
Remove-WjmJunction | Inspect, then detach with Directory.Delete(path, $false) and rmdir fallback |
Set-WjmJunctionTarget | Remove and recreate; restore the previous target on failure when it still exists |
Repair-WjmJunction | Recreate a missing junction, retarget a stale one, no-op when healthy |
Remove-WjmEmptyTargetDirectory | Delete a target only when empty, unprotected, non-root, and free of nested reparse points |
Clear-WjmStaleJunctions | Iterate 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.
| Function | Behavior |
|---|---|
ConvertTo-WjmInventoryRecord | Project a junction record onto the inventory schema |
Export-WjmInventory | Write JSON or CSV, or return a preview when -DryRun |
Import-WjmInventory | Parse and normalize a JSON inventory or a bare array |
Restore-WjmInventory | Recreate only missing, unprotected links whose targets still exist |
Backup-WjmInventory | Write 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.
| Function | Returns |
|---|---|
Get-WjmCatalog | Array of module objects, each with Items |
Get-WjmAllActions | Flat 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-WjmCatalogTotal | Number 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.
| Function | Behavior |
|---|---|
Initialize-WjmLogger | Create 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-WjmLogEnabled | Current enabled state |
Get-WjmLogPath | Active 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.
| Function | Purpose |
|---|---|
Initialize-WjmUi | Build the palette or a no-color equivalent |
Get-WjmPalette | Lazy-initialize and return the palette |
Format-WjmTruncate | Clip text with an ellipsis |
Get-WjmUiWidth | Clamp the frame width to the console |
Build-WjmHeaderBlock | Header with brand, subtitle, and status pills |
Build-WjmFooterBlock | Rule, toast, and hint line |
Set-WjmStatus / Get-WjmStatus | Session toast state |
Clear-WjmScreen / Write-WjmFrame | Full 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.
Related documentation
- Architecture — how the modules fit together.
- Action catalog — modules, actions, and search.
- Testing — how each module is exercised.
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:
| Field | Type | Meaning |
|---|---|---|
MenuKey | string | Top-level TUI hotkey (1–5) |
ModuleId | string | Stable machine identifier (scan, manage, clean, backup, settings) |
Name | string | Display name |
Description | string | One-line purpose shown in the TUI |
Optional | bool | Reserved for future optional modules; currently $false |
Items | array | Ordered actions |
Each action item has:
| Field | Type | Meaning |
|---|---|---|
Id | string | Stable action identifier, unique across the catalog |
MenuKey | string | Hotkey inside the module (1–6) |
Label | string | Display label |
Action | string | Dispatcher key used by Invoke-WjmAction |
NeedsInput | bool | Whether the action prompts for a path or file |
Mutates | bool | Whether 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.
| Key | Action ID | Label | Input | Mutates |
|---|---|---|---|---|
1 | scan-standard | Scan Standard Locations | No | No |
2 | scan-path | Scan a Custom Directory | Yes | No |
3 | inspect | Inspect One Junction | Yes | No |
4 | stale-report | Stale Junction Report | No | No |
5 | summary | Inventory Summary Dashboard | No | No |
6 | verify | Verify Junction Health | No | No |
2. Create & Manage (manage)
Create, retarget, repair, and remove junctions. All mutating.
| Key | Action ID | Label | Input | Mutates |
|---|---|---|---|---|
1 | create | Create a New Junction | Yes | Yes |
2 | retarget | Retarget an Existing Junction | Yes | Yes |
3 | repair | Repair a Junction | Yes | Yes |
4 | remove | Remove a Junction | Yes | Yes |
5 | remove-empty-target | Delete an Empty Target Directory | Yes | Yes |
3. Clean & Repair (clean)
Remove stale links and optionally reclaim empty targets. All mutating.
| Key | Action ID | Label | Input | Mutates |
|---|---|---|---|---|
1 | clean-stale | Clean All Stale Junctions | No | Yes |
2 | clean-orphaned | Clean Orphaned (Missing Target) | No | Yes |
3 | clean-empty | Clean Empty-Target Junctions | No | Yes |
4 | clean-stale-empty | Clean Stale + Empty Targets | No | Yes |
4. Backup & Export (backup)
Export inventory, back up, and restore links. Only restore mutates.
| Key | Action ID | Label | Input | Mutates |
|---|---|---|---|---|
1 | export-json | Export Inventory to JSON | Yes | No |
2 | export-csv | Export Inventory to CSV | Yes | No |
3 | backup | Back Up Inventory Snapshot | No | No |
4 | import-preview | Preview an Inventory File | Yes | No |
5 | restore | Restore Junctions from Backup | Yes | Yes |
5. Settings & Safety (settings)
Inspect the protection policy, scan roots, logs, and version. All read-only.
| Key | Action ID | Label | Input | Mutates |
|---|---|---|---|---|
1 | list-protected | Show Protected Paths | No | No |
2 | show-roots | Show Standard Scan Roots | No | No |
3 | open-logs | Open Logs Folder | No | No |
4 | about | About & Version | No | No |
Catalog invariants
These are enforced by 02_Catalog.Tests.ps1:
- Exactly 5 modules.
- Exactly 24 actions.
- Module IDs are stable and unique.
- Action IDs are stable and unique across all modules.
- Every action has
Id,MenuKey,Label,Action,NeedsInput, andMutates. - Every action is reachable from its module menu key.
Mutatesis$truefor every operation that can change the filesystem and$falsefor every read-only action.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:
- Add or remove the item in
Get-WjmCatalog. - Add or remove the matching branch in
Invoke-WjmActioninsrc/menu.ps1. - Add a headless flag and dispatch branch if the action should be scriptable.
- Update the module/action tables in this page and the user documentation.
- Update the literal counts in
README.mdandREADME.txtif the total changes. - Update
02_Catalog.Tests.ps1and01_SyntaxAndDocs.Tests.ps1. - Run the full suite.
The catalog is intentionally data-only. Keep behavior in src/menu.ps1 or the core modules, not in the hashtables.
Related documentation
- 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
| Flag | Effect |
|---|---|
--list | List every discovered suite with its number, slug, and title |
--all | Run every suite |
--suite <names> | Run suites by number, slug, or title keyword; comma- or semicolon-separated |
--pester | Force Pester 5; fail if it is not installed |
--native | Force the bundled engine |
--verbose | Show per-case timings |
--no-pause | Skip the return-to-menu pause in the TUI |
The runner exits 0 when every case passes and 1 when any case fails.
TUI keys
| Key | Action |
|---|---|
↑ / ↓ | Move the selection |
Enter | Run the selected suite |
1–9, 0 | Jump to a suite by number |
A | Run all suites |
P | Toggle Pester 5 / native engine (when Pester is available) |
V | Toggle verbose timings |
Q / Esc | Quit |
Suite inventory
| Suite | Slug | Focus |
|---|---|---|
01_SyntaxAndDocs | 01_syntaxanddocs | Parses every project .ps1; entry points, launcher hygiene, documentation set, catalog-count alignment |
02_Catalog | 02_catalog | Five modules, twenty-four actions, unique IDs, required fields, search, menu reachability |
03_Paths | 03_paths | Normalization, drive roots, protected paths, scan roots, containment, validation |
04_Junctions | 04_junctions | Missing/not-a-junction/active/orphaned/empty classification, discovery, summary, stale filter |
05_Operations | 05_operations | Create, retarget rollback, repair, remove, empty-target deletion, dry-run, cleanup |
06_Inventory | 06_inventory | JSON/CSV export, empty CSV, dry-run export, round-trip import, restore guards, backup |
07_Cli | 07_cli | Help, list, search, inspect, create/retarget/remove, dry-run cleanup, usage errors, destructive refusal |
08_CrossVolume | 08_crossvolume | Alternate-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;ShouldwithBe,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:
| Function | Purpose |
|---|---|
Get-WjmTestRepoRoot | Resolve the repository root from tests/helpers |
Get-WjmTestCoreModulePaths | Read src/core/manifest.ps1 and return the product’s load order |
Invoke-WjmNativeSuiteFile | Run 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.
| Function | Purpose |
|---|---|
New-WjmTestWorkspace | Create a temp workspace with target, target2, link, and link2 |
Get-WjmTestAlternateVolumeRoot | Return a second ready fixed volume, or '' |
New-WjmTestFile | Write a fixture file, creating parents |
New-WjmTestJunction | Try New-Item -ItemType Junction, then mklink /J for broken-target cases |
Remove-WjmTestJunction | Detach a link non-recursively, then fall back to rmdir |
Remove-WjmTestWorkspace | Detach links first, then remove the workspace tree |
Design rules
- Attempt, then inspect. A test performs the operation and asserts on the native result instead of skipping because a volume is “not NTFS”.
- Links live where creation is most likely to succeed. Workspaces use the current user’s temp directory.
- 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.
- 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
- Add
tests/suites/NN_Name.Tests.ps1. - Start with
#Requires -Version 7.0. - In
BeforeAll, resolve the repo root, loadTestHarness.ps1andJunctionTestKit.ps1, then dot-source every core module viaGet-WjmTestCoreModulePaths. - Use
DescribeandIt. UseBeforeEach/AfterEachfor fixtures and cleanup. - Use junction fixtures for filesystem cases and plain temp files where a junction is not required.
- Assert behavior and result fields, not console formatting.
- 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
| Symptom | Cause | Fix |
|---|---|---|
Pester 5+ is not installed | --pester was forced | Install Pester 5 or use --native |
| A suite passes in Pester but fails natively | The suite uses a Pester feature outside the shim subset | Rewrite the assertion using the supported set |
| Junction tests fail with access denied | The temp location or parent requires different ACLs | Run the session where the user can write the temp tree |
| Cross-volume case is skipped-looking | No second fixed volume exists | Expected; the test asserts on the native outcome, not a skip |
Related documentation
- Architecture — module layering and result contracts.
- Core modules — the functions the suites exercise.
- Action catalog — catalog invariants checked by suite 02.
- Research: junction behavior — platform evidence behind the fixture rules.
Contributing
This page describes how to make a change that stays consistent with the project’s structure, safety rules, and test expectations.
Contribution principles
| Principle | What it means in practice |
|---|---|
| Safety first | Never weaken the protected-path policy or add a mutation path that bypasses validation |
| One catalog | Do not hard-code module or action lists outside src/core/catalog.ps1 |
| Native behavior wins | Do not add a filesystem-type gate; attempt the operation and surface the result |
| Dry-run is core-level | Every new mutating function accepts -DryRun and validates before acting |
| Portable | No installer, no hard-coded tool paths, no hidden elevation, no network dependency |
| Local verification | Changes are verified locally with the test runner before they are considered complete |
Prerequisites
- Windows 11
- PowerShell 7.x (
pwsh) available onPATH - 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 Latestand$ErrorActionPreference = 'Stop'at entry points. - Name product functions with the
Wjmnoun 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
-LiteralPathfor 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.ps1andmenu.ps1should 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:
- Catalog — add the module/item entry in
src/core/catalog.ps1. - TUI dispatch — add the branch in
Invoke-WjmActioninsrc/menu.ps1. - CLI dispatch — add the flag parser and
Invoke-WjmCliModebranch if it should be scriptable. - Core — add or reuse a core function. If it mutates, accept
-DryRunand validate first. - Tests — add a case to the relevant suite and update
02_Catalog.Tests.ps1. - Documentation — update this developer guide and the user-facing reference.
- 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
-DryRunand 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
| Area | Question |
|---|---|
| Scope | Does the change do one coherent thing? |
| Safety | Could it mutate a protected path or the wrong filesystem object? |
| Consistency | Did the catalog, CLI, TUI, tests, and docs move together? |
| Portability | Did any hard-coded install path, username, or machine-specific value slip in? |
| Secrets | Is any sensitive value present in a tracked file or log? |
| Verification | Did the full suite pass, and the docs build if pages changed? |
Related documentation
- Architecture — layering and invariants.
- Core modules — function reference.
- Action catalog — how to change the surface.
- Testing — suites, engines, and fixtures.
- Research: junction behavior — platform constraints.
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:
- What is a junction at the filesystem level?
- Which volumes can host a junction link, and which can host a target?
- How do broken junctions behave when inspected and removed?
- Which PowerShell and .NET calls are safe for creation, inspection, and detachment?
- 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.
Junction vs symbolic link vs mount point
| Aspect | Junction | Directory symbolic link | Volume mount point |
|---|---|---|---|
| Reparse tag | IO_REPARSE_TAG_MOUNT_POINT | IO_REPARSE_TAG_SYMLINK | IO_REPARSE_TAG_MOUNT_POINT |
| Target kind | Local directory path | Local or remote path | Volume |
| Remote target | No | Yes (UNC) | No |
| Creation privilege | No symbolic-link privilege required | Symbolic-link privilege or Developer Mode | Typically administrative |
| Common creator | mklink /J, New-Item -ItemType Junction | mklink /D, New-Item -ItemType SymbolicLink | mountvol, 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 role | Requirement | Evidence |
|---|---|---|
| Host of the junction link | Must support reparse points | NTFS and ReFS support reparse points; FAT32 and exFAT do not |
| Host of the target directory | Any local filesystem the path can reach | The 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.
| Scenario | Call | Observed result |
|---|---|---|
| Link on an NTFS system volume targeting a directory on a FAT32 data volume | New-Item -ItemType Junction | Succeeds; the link resolves to the target |
| Link path placed directly on the FAT32 data volume | New-Item -ItemType Junction | Fails; Windows returns a native error such as “Incorrect function” or an NTFS-required message |
| Target directory missing | Get-Item on the link | Returns the link entry with LinkType = 'Junction' |
| Target directory missing | New-Item -ItemType Junction | Fails because the target must exist |
| Target directory missing | cmd /c mklink /J | Creates 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
| Decision | Reason |
|---|---|
| Status comes from target existence and content, not volume type | The link and target may live on different filesystems |
| Create, retarget, and repair attempt the native call | Only Windows knows whether the path is accepted |
| Removal uses non-recursive delete | A recursive delete could follow the link into the target |
| Inspection uses the reparse entry, not the target | Broken links must remain visible and removable |
| Restore checks target existence and protection, not volume type | Targets may live anywhere local |
| Test fixtures attempt and assert on native results | Avoids false skips and mirrors production behavior |
Canonical references
- Reparse points
- Reparse point tags
- Hard links and junctions
- File attribute constants
mklinkcommandNew-ItemGet-ItemDirectory.Delete
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.