1

I am using forfiles /S to iterate over a directory tree. I'm running it directly in the command prompt.
To find out the current directory I want to expand the built-in variable %CD%, but not immediately (showing the current directory of the command prompt instance that executes forfiles), but with % escaped in a way that %CD% is expanded by the command prompt instance in the body of forfiles.

forfiles /S /P "D:\Data" /M "*.txt" /C "cmd /C echo %CD%"

Is there a way to escape % and so to kind of hide it from the main command interpreter instance?
I tried %% (that works fine within a batch file), ^%, \%, and even enclosing %CD% in plain and escaped quotes ("%CD%"/\"%CD%\"), but I had no success so far.

I know I could use delayed expansion like the following, but I want to avoid it:

forfiles /S /P "D:\Data" /M "*.txt" /C "cmd /V:ON /C echo !CD!"
Community
  • 1
  • 1
aschipfl
  • 33,626
  • 12
  • 54
  • 99

1 Answers1

1

From command line, if you don't escape the percent sign, the variable is directly replaced with its value, but if you escape it (with a caret),

forfiles /S /P "D:\Data" /M "*.txt" /C "cmd /C echo ^%CD^%" 

as the command is enclosed in quotes (forfiles requirement in your command) the carets are not removed and the literal %cd% (there are carets escaping the percent signs) is echoed for each file.

The simplest solution is not to escape the percent signs, but use the special character management in forfiles command, replacing the problematic % with its ASCII code value

forfiles /S /P "D:\Data" /M "*.txt" /C "cmd /C echo 0x25cd0x25"

Or, you can define the command inside a variable and then use it

set myCommand=cmd /c echo ^%cd^%
forfiles /S /P "D:\Data" /M "*.txt" /C "%myCommand%"
MC ND
  • 69,615
  • 8
  • 84
  • 126
  • Thank you! If I get it right, the second work-around using a variable is not limited to `forfiles`, it may also be used for other commands that take quoted strings. – aschipfl Aug 19 '15 at 08:24