Write multi-line variable to .txt (CMD, NO .bat)

What am I doing wrong?

You need to surround the last echo with ( and )

(echo %t%) > paths.txt

Corrected batch file (test.cmd):

@echo off
setlocal
set t=%PATH:;=^&echo.%
echo %t%
(echo %t%) > paths.txt
:endendlocal

Example usage:

> test
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\apps\WSCC\Sysinternals Suite
C:\apps\WSCC\NirSoft Utilities
C:\apps\Calibre\
C:\apps\Git\cmd
C:\apps\Git\mingw64\bin
C:\apps\Git\usr\bin
C:\apps\nodejs\
C:\Users\DavidPostill\AppData\Roaming\npm
> type paths.txt
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\apps\WSCC\Sysinternals Suite
C:\apps\WSCC\NirSoft Utilities
C:\apps\Calibre\
C:\apps\Git\cmd
C:\apps\Git\mingw64\bin
C:\apps\Git\usr\bin
C:\apps\nodejs\
C:\Users\DavidPostill\AppData\Roaming\npm

A simpler solution

This solution does not require any brackets in the path to be escaped.

test.cmd:

@echo off
setlocal
for %%i in ("%path:;=";"%") do (
  echo %%~i >> paths.txt
)
:endendlocal

And from the command line:

for %i in ("%path:;=";"%") do echo %~i >> paths.txt

Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • syntax-brackets - Using parenthesis/brackets to group expressions