How can I write quoted Environment Variables to a file using cmd?

Viewed 61

I can't figure out how to write "%PROGRAMFILES%" literally to a file using Windows Command Prompt.

What I've tried:

C:\Users\lxvs> echo "%PROGRAMFILES%" > test
C:\Users\lxvs> type test
"C:\Program Files"

C:\Users\lxvs> echo ^%PROGRAMFILES^% > test
C:\Users\lxvs> type test
%PROGRAMFILES%

C:\Users\lxvs> echo "^%PROGRAMFILES^%" > test
C:\Users\lxvs> type test
"^%PROGRAMFILES^%"

C:\Users\lxvs> echo "%%PROGRAMFILES%%" > test
C:\Users\lxvs> type test
"%C:\Program Files%"

Is there a way to approach it?

2 Answers

Escape the quotes, so that the carets inside get parsed and removed.

C:\etc>echo ^"%^ProgramFiles%^" >test

C:\etc>type test
"%ProgramFiles%"

C:\etc>

Escape both " and %

(echo ^"^%programfiles^%^")>test & type test

or similarly to the other answer, but moving the escape to before the last %:

(echo ^"%programfiles^%^")>test & type test

In a batch-file however, double up on the %

(echo "%%programfiles%%")>test & type test
Related