Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does forfiles swallow the first argument of the command?

Tags:

batch-file

cmd

I'm trying to do something similar to Get Visual Studio to run a T4 Template on every build using cmd's forfiles to transform each template in VS2008.

If I execute

forfiles /m "*.tt" /s /c "\"%CommonProgramFiles(x86)%\Microsoft Shared\TextTemplating\1.2\TextTransform.exe\" @file"

then I get TextTransform.exe's error message (the screen of text explaining what to pass it as arguments).

If I instead execute

forfiles /m "*.tt" /s /c "cmd /c echo Transforming @path && \"%CommonProgramFiles(x86)%\Microsoft Shared\TextTemplating\1.2\TextTransform.exe\" @file"

then it works perfectly.

In order to debug this, I created a simple command-line program called debugargs which simply prints the number of arguments it receives and their values. Then some experimentation shows that the first form of directly passing the command to forfiles causes the first argument to be swallowed. E.g.

forfiles /m "*.tt" /s /c "debugargs.exe 1 2 3"

gives output

2 arguments supplied
#1: 2
#2: 3

The documentation I've been able to find is quite sparse, and I don't see any mention of this as a possibility. Is it just an obscure bug, or am I missing something?

like image 614
Peter Taylor Avatar asked Jan 25 '26 00:01

Peter Taylor


1 Answers

This appears to be a bug in the way forfiles invokes .exes. On a hunch I extended my debugargs program to print the full command line.

X:\MyProject>forfiles /m "*.tt" /s /c "debugargs.exe 1 2 @file"

2 arguments supplied
#1: 2
#2: Urls.tt
Full command line: 1 2 "Urls.tt"

So the most appropriate workaround would be to double the executable name:

forfiles /m "*.tt" /s /c "debugargs.exe debugargs.exe 1 2 @file"

The alternative workaround is to invoke with cmd /c. However, note here that if you need to quote the executable's path (e.g. because it contains a space), you'll need an extra workaround of prepending @:

forfiles /m "*.tt" /s /c "cmd /c @\"debugargs.exe\" 1 2 @file"
like image 75
Peter Taylor Avatar answered Jan 26 '26 23:01

Peter Taylor