'How do I run test-path on all paths in the system variable PATH using powershell?
I would like to run the Test-Path, or something similar the completes my purpose to find the invalid paths in my path variable.
The main thing I have done is search for
test path system variable for invalid entries
This did not find anything.
This example is just to show I have tried something, but I don't really know what the best command it.
Test-Path -Path %Path% -PathType Any
Update
These scripts enabled my to find a couple bad paths and fix them
Solution 1:[1]
Building on Mathias R. Jessen's great solution in a comment:
# Output those PATH entries that refer to nonexistent dirs.
# Works on both Windows and Unix-like platforms.
$env:PATH -split [IO.Path]::PathSeparator -ne '' |
Where-Object { -not (Test-Path $_) }
Using the all uppercase form
PATHof the variable name and[IO.Path]::PathSeparatoras the separator to-splitby makes the command cross-platform:On Unix-like platforms environment variable names are case-sensitive, so using
$env:PATH(all-upercase) is required; by contrast, Windows is not case-sensitive, so$env:PATHworks there too, even though the actual case of the name isPath.On Unix-like platforms,
:separates the entries in$env:PATH, whereas it is;on Windows -[IO.Path]::PathSeparatorreturns the platform-appropriate character.
-ne ''filters out any empty tokens resulting from the-splitoperation, which could result from directly adjacent separators in the variable value (e.g.,;;) - such empty entries have no effect and can be ignored.- Note: With a an array as the LHS, such as returned by
-split, PowerShell comparison operators such as-eqand-neact as filters and return an array of matching items rather than a Boolean - see about_Comparison_Operators.
- Note: With a an array as the LHS, such as returned by
The
Where-Objectcall filters the input directory paths down to those that do not exist, and outputs them (which prints to the display by default).- Note that, strictly speaking,
Test-Path's first positional parameter is-Path, which interprets its argument as a wildcard expression. - For full robustness,
Test-Path -LiteralPath $_is needed, to rule out inadvertent interpretation of literal paths that happen to contain[as wildcards - though with entries in$env:PATHthat seems unlikely.
- Note that, strictly speaking,
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
