windows cmd: problems with for /f with a quoted command with quoted parameters

Here are two solutions.

1) has surrounding double quotes and removed ^ escape character.
2) uses find as it is on the path.

for /f %%a in ('""%systemRoot%\system32\find.exe" /c /v "" < "c:\something.txt""') do @echo %%a

for /f %%a in (' find.exe /c /v "" ^< "c:\something.txt"') do @echo %%a

It’s to do with launching an extra cmd process to run the command-line inside the for command.

Curiously, these three commands fail differently in an even simpler context.

for /f %%a in (' "c:\windows\system32\find.exe" /c /v ""  something.txt ') do @echo %%a

The system cannot find the path specified.

for /f %%a in (' "c:\windows\system32\findstr.exe" /n "."  something.txt ') do @echo %%a

The directory name is invalid.

for /f %%a in (' "c:\windows\notepad" "something.txt" ') do @echo %%a

‘c:\windows\notepad” “something.txt’ is not recognized as an internal or external command, operable program or batch file.

This last one gives a clue that the outer quotes are being stripped.

Windows 8.1 32 bit

I think the quote issue is described here in cmd /? when a child process is invoked:

If /C or /K is specified, then the remainder of the command line after
the switch is processed as a command line, where the following logic is
used to process quote (") characters:

    1.  If all of the following conditions are met, then quote characters
        on the command line are preserved:

        - no /S switch
        - exactly two quote characters
        - no special characters between the two quote characters,
          where special is one of: &<>()@^|
        - there are one or more whitespace characters between the
          two quote characters
        - the string between the two quote characters is the name
          of an executable file.

    2.  Otherwise, old behavior is to see if the first character is
        a quote character and if so, strip the leading character and
        remove the last quote character on the command line, preserving
        any text after the last quote character.

Leave a Comment