Search code examples
windowsfor-loopbatch-filedouble-quotesmultiple-arguments

Passing Multiple Arguments in a Batch FOR loop using Double Quotes?


I'm using a MediaInfo CLI in a batch script and I don't know what the issue is, but I cannot get this command to work if I use a folder path that has spaces in it. I'm not new to batch scripts and have created hundreds over the years. Normally I would think that using double quotes would solve the issue, but I know it's something else related to using the "for /f" command and passing multiple arguments with double quotes. I've tried everything I could think of but still can't get it to work if I'm using a path with spaces. Without spaces it works just fine, just not with spaces.

Please Note that this is not the full batch script and is only a snippet of the offending code. I also changed the double "%%" variables to single "%" to make it easier for testing on the command line.

Also, in my batch script, instead of using "echo" I am outputting to a variable, which is why I must use the "for" command. All of which is irrelevant to this specific issue.

WORKING EXAMPLES

for /f %g in ('C:\MediaInfo.exe "--Inform=General;%MenuCount%" "D:\Some Folder\filename.mkv"') do echo %g

.

for /f "usebackq delims=" %g in (`C:\MediaInfo.exe "--Inform=General;%MenuCount%" "D:\Some Folder\filename.mkv"`) do echo %g

.

NOT WORKING EXAMPLES

for /f %g in ('"C:\folder with spaces\MediaInfo.exe" "--Inform=General;%MenuCount%" "D:\Some Folder\filename.mkv"') do echo %g

.

for /f "usebackq delims=" %g in (`C:\folder with spaces\MediaInfo.exe "--Inform=General;%MenuCount%" "D:\Some Folder\filename.mkv"`) do echo %g

Both of the "NOT WORKING" commands result in the same error...

'C:\folder' is not recognized as an internal or external command, operable program or batch file.


Solution

  • The command within the set (that is the parenthesised part before do) of a for /F loop is actually executed by cmd /C, which may remove potential quotes depending on their positions. For instance, in the command line:

    for /f "delims=" %g in ('"C:\folder with spaces\MediaInfo.exe" "--Inform=General;%MenuCount%" "D:\Some Folder\filename.mkv"') do echo %g
    

    the outer pair of quotes is removed, leaving behind the invalid command line:

    C:\folder with spaces\MediaInfo.exe" "--Inform=General;%MenuCount%" "D:\Some Folder\filename.mkv
    

    If you now add an additional pair of quotes, it will work. You may even escape these quotes not to have to alter any other escaping in case:

    for /f "delims=" %g in ('^""C:\folder with spaces\MediaInfo.exe" "--Inform=General;%MenuCount%" "D:\Some Folder\filename.mkv"^"') do echo %g