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

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.