Skip to content

some enhancements #1

@roblatour

Description

@roblatour

Hi,

First, thanks for making this script available - it was very helpful.

However, prior to running it, I ran the code through copilot gpt-5 and it came up with some potential issues and the associated fixes.

Included below are how it summarized them.

Also, included below is the revised script it produced, which I ran on my own machine and seems to have worked well for me.

Hope this will help, and again - thanks for posting.

Here is what the AI said:

Summary

While reviewing the repository's PowerShell script for PATH cleanup (path-cleanup.ps1), several issues were identified that could lead to accidental removal of valid entries or change PATH resolution precedence. With this contribution, the script was revised to:

  • Safely handle quoted and whitespace-padded PATH entries
  • Preserve drive roots like C:\ during normalization
  • Deduplicate within User and System scopes independently, then remove cross-scope duplicates in a way that preserves System precedence
  • Allow -DryRun without requiring Administrator, while still requiring admin when applying changes
  • Improve normalization and existence checks to reduce false negatives

These changes make previewing and applying PATH cleanup safer and more predictable, while retaining backups for rollback.

Problems identified

  1. Quoted PATH entries were misclassified as invalid
  • Many installers add entries like "C:\\Program Files\\nodejs\\". The script did not strip surrounding quotes before testing existence, so Test-Path could fail, and valid entries could be removed.
  1. Drive-root trimming bug
  • Normalization used a blanket trim of trailing slashes. A bare drive root C:\ would become C:, changing the meaning and likely failing validation.
  1. Cross-scope dedup changed PATH precedence
  • All entries (User + System) were merged and deduplicated together, then re-categorized. If the same folder was present in both, the first-seen copy could win, unintentionally changing the effective PATH resolution precedence between System and User.
  1. -DryRun unnecessarily required Administrator
  • The script exited when not elevated, even for -DryRun, preventing safe previews without admin rights.
  1. Normalization and validation gaps
  • Input wasn’t trimmed consistently, forward slashes weren’t normalized before existence checks, and quotes weren’t stripped prior to expansion, increasing the chance of false negatives.
  1. Risky scope re-categorization heuristics
  • The script attempted to move entries across scopes based on heuristics. This can misclassify certain paths (e.g., vendor tools installed under user profile) and surprise users by moving entries between User and System PATH.
  1. Minor/documentation items (not blockers)
  • README restore example could use Get-Content -Raw for robustness.
  • Extremely long PATH lengths are not preflight-checked (we rely on the set call’s exception handling).
  • Test-IsUserPath used wildcard matching; safe, but the rebalancing step should be opt-in.

Changes implemented

  • Admin handling

    • Introduced $isAdmin gate: -DryRun is allowed without elevation. Admin is still required to write Machine PATH.
  • Robust path cleaning and normalization

    • Added Clean-InputPath to trim whitespace and strip surrounding quotes.
    • Normalize-Path now expands environment variables, converts forward slashes to backslashes, preserves drive roots (e.g., C:\), normalizes C: to C:\, and trims trailing slashes safely for non-root paths.
    • Test-PathExists now cleans and expands before Test-Path, reducing false negatives.
  • Precedence-safe deduplication

    • New per-scope dedup: remove duplicates within User and System separately, preserving original order.
    • Cross-scope dedup then removes User entries that are duplicates of System entries, preserving System precedence in the effective PATH.
    • No cross-scope re-categorization is performed by default (safer behavior).
  • Output/summary improvements

    • Summaries reflect per-scope dedup, cross-scope duplicates removed, and invalid paths found.

File(s) touched

  • path-cleanup.ps1
    • Added: Clean-InputPath, Get-UniquePreserveOrder
    • Updated: admin gate; Normalize-Path; Test-PathExists; main pipeline to dedup/validate per scope and preserve System precedence

Backward compatibility and behavior

  • Default behavior now preserves the original scope (User vs System) for existing entries. This avoids moving items across scopes unless explicitly requested (future opt-in flag could support rebalancing).
  • Effective PATH resolution remains predictable, with System-preferred duplicates kept over User duplicates.
  • Backups can be created even in -DryRun mode for convenient, non-destructive review.

How to test

  1. Preview (no changes):
powershell -NoProfile -ExecutionPolicy Bypass -File ".\path-cleanup.ps1" -DryRun -Verbose
  1. Create backup and preview (no changes):
powershell -NoProfile -ExecutionPolicy Bypass -File ".\path-cleanup.ps1" -DryRun -Backup
  1. Apply with backup (run PowerShell as Administrator):
powershell -NoProfile -ExecutionPolicy Bypass -File ".\path-cleanup.ps1" -Backup -Verbose
  1. Verify:
  • Check the console output for counts of duplicates and invalid paths.
  • Confirm a PATH_Backup_yyyyMMdd_HHmmss folder exists with USER_PATH.txt and SYSTEM_PATH.txt.
  • Open a new terminal and validate expected entries are present and invalid ones removed.

Follow-ups (nice-to-have)

  • Add an opt-in flag (e.g., -RebalanceScopes) that uses the existing Test-IsUserPath heuristic to move entries between scopes only when requested.
  • Remove or gate the currently unused Test-IsUserPath to avoid confusion.
  • Update README restore examples to use Get-Content -Raw for robustness.
  • Optionally add canonicalization for 8.3 short names vs long paths and a preflight check/warning for very long PATH values.
  • Optional validator to flag obviously malformed tokens (e.g., concatenated entries without semicolons) before removal.

Rationale

These changes minimize risk during PATH cleanup, improve correctness, and preserve user expectations about PATH resolution order and scope, while keeping a clear preview and easy rollback path.

Here is the revised shell (zipped)

path-cleanup.zip

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions