Listing folder paths from %PATH% to a file, one per line

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
iSAWaUFO
Posts: 1
Joined: 13 Jun 2013 18:11

Listing folder paths from %PATH% to a file, one per line

#1 Post by iSAWaUFO » 13 Jun 2013 18:56

I frequently need to check the list of folders in the PATH environment variable.
I need to see if folders exist and in what order they are referenced.

As I searched in the forums for examples on how to list out %PATH% in a readable, 1 folder path per line, listing. I was able to piece this command together from various examples:

> echo %PATH:;=&echo.%
C:\windows\system32
C:\windows
C:\windows\System32\Wbem
C:\windows\System32\WindowsPowerShell\v1.0\

I don't understand how the ampersand (&) works in this context, except that it must run the command and insert its output, a newline (CR-LF) into the text substitution syntax, thus substituting newlines for semicolons in the value of %PATH%.

This actually works great, as long as you just type it at the command line, and is very handy because it is short and easy.

The problem is when I want to redirect the output of the list to a file. Only the last item goes to the file and the rest print to the screen. It's very perplexing!

> echo %PATH:;=&echo.% > listing.txt
C:\windows\system32
C:\windows
C:\windows\System32\Wbem

> type listing.txt
C:\windows\System32\WindowsPowerShell\v1.0\

I would love to know why this behaves so stangely and how can I get this list to a file.

Appending 2>&1 to the end of the command makes no difference, nor using >> instead of >

I had also tried
for /d %a in (%PATH%) do @echo %a
which sort of works, unless any folders have embedded spaces in the paths, causing the folder paths to get split into multiple lines.

Aacini
Expert
Posts: 1932
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: Listing folder paths from %PATH% to a file, one per line

#2 Post by Aacini » 13 Jun 2013 19:39

The & inserted at the end of each part separate the line in several commands. This way, your redirection to a file works only over the last command. Use this method instead:

Code: Select all

( echo %PATH:;=&echo.% ) > listing.txt

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Listing folder paths from %PATH% to a file, one per line

#3 Post by dbenham » 13 Jun 2013 22:47

@Aacini - that often works, but there are various situations where it can fail: unquoted special chars in a path, semicolon within a quoted path.

jeb posted both another simple one liner that often works, and a fairly complex batch script that always works on StackOverflow: 'Pretty print' windows %PATH% variable - how to split on ';' in CMD shell

Dave Benham

Post Reply