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.