Peter Taylor
Peter Taylor

Reputation: 5086

Why does forfiles swallow the first argument of the command?

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?

Upvotes: 3

Views: 2373

Answers (3)

jamieg
jamieg

Reputation: 189

I've been struggling with this as well. The work-around I've found is to just add an extra space between the command and first argument! So where I was trying to do:

FORFILES /s /m *.dll /c "python \"c:\path\to\script.py\" -t arg1 etc"

python was trying to find file "arg1" to execute, but if I just change it to:

FORFILES /s /m *.dll /c "python  \"c:\path\to\script.py\" -t arg1 etc"

this actually works!

Upvotes: 0

Peter Taylor
Peter Taylor

Reputation: 5086

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"

Upvotes: 3

Bill_Stewart
Bill_Stewart

Reputation: 24585

I reproduced the behavior in forfiles as well. You can work around by using cmd /c before the command, or you could transition to PowerShell, where the equivalent command would be something like this (not tested):

get-childitem . -filter "*.tt" -recurse | foreach-object {
  & "${ENV:CommonProgramFiles(x86)}\Microsoft Shared\TextTemplating\1.2\TextTransform.exe" "`"$($_.Name)`""
}

Bill

Upvotes: 0

Related Questions