I came up with the following (to be executed on the command line)
Code: Select all
for %P in ("%path:;=" "%") do @echo(%~P
It worked great, and I was curious if anyone had posted it before.
Of course jeb has already posted a nearly identical solution at 'Pretty print' windows %PATH% variable - how to split on ';' in CMD shell
jeb goes on to show how the solution fails if the PATH contains quoted ; within it. The problem is ; is a valid character for folder names, and must be quoted in the PATH. He posted a safe solution for any situation on the same thread. I won't post his safe solution here (nor some minor improvements I suggested). Just follow the link.
I then started thinking about PATH, and how it is common practice to append to PATH using something like:
Code: Select all
set PATH=%PATH%;c:\new_path\
Even Microsoft recommends the operation:
Code: Select all
C:\>help path
Displays or sets a search path for executable files.
PATH [[drive:]path[;...][;%PATH%]
PATH ;
Type PATH ; to clear all search-path settings and direct cmd.exe to search
only in the current directory.
Type PATH without parameters to display the current path.
Including %PATH% in the new path setting causes the old path to be
appended to the new setting.
But this will fail if the PATH contains any of the following valid unquoted path characters: ^ &
This fix is not reliable:
Code: Select all
set "path=%path%;\new_path"
Here is a valid PATH that wont extend properly either with or without enclosing quotes:
Code: Select all
PATH=c:\This & That;"c:\A path with ; semicolon";c:\a third path
The solution is fairly simple - make sure the PATH is expanded using delayed expansion.
Here is a simple function that will reliably append any path to the existing PATH as long as it is not called while delayed expansion is enabled. (thanks Ed for pointing out this limitation in your post below).
Code: Select all
@echo off
:PathAdd pathVar
:: pathVar is the name of a variable containing the new path to append to PATH
setlocal enableDelayedExpansion
for /f "tokens=* delims=;" %%N in ("!%~1!") do (
for /f "tokens=* delims=;" %%P in ("!PATH!") do (
endlocal
set path=%%P;%%N
)
)
exit /b
Dave Benham