Search code examples
windowsshellbatch-filecmd

Traverse path variable with FOR in Windows


My faithful path traversal method no longer works - it sees spaces as delimiters. It's been a while since I needed to do batch programming.
When using the FOR loop, the only one that allows delimiters are the FOR /F option.
I don't want to create a temporary file containing the path, was hoping to do something like below:

C:\Users>for /f "delims=;" %i in %path% do echo %i
C:\Program was unexpected at this time.

C:\Users>for /f "delims=;" %i in (%path%) do echo %i
\Common was unexpected at this time.

C:\Users>for /f "delims=;" %i in 'foo;bar' do echo %i
'foo was unexpected at this time.

Solution

  • @echo off
    setlocal EnableDelayedExpansion
    
    for /F "delims=" %%a in (^"!path:^;^=^
    % Do NOT remove this line %
    !^") do echo %%a
    

    Output example:

    C:\Program Files (x86)\AMD APP\bin\x86_64
    C:\Program Files (x86)\AMD APP\bin\x86
    C:\Windows\system32
    C:\Windows
    C:\Windows\System32\Wbem
    C:\Windows\System32\WindowsPowerShell\v1.0\
    C:\Program Files (x86)\Windows Live\Shared
    C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static
    C:\Program Files\Bandizip\7z