Having a batch file that uses 7-Zip to "look" into a zip-file if it contains a certain file.
"C:\Program Files\7-Zip\7z.exe" l "FolderName\archive.zip" "file.cmd"
But putting it into a for-loop it produces the error: 'cannot find "C:\Program" '. Writing %ProgramFiles% also makes no difference.
for /F "delims=" %%a in ('"C:\Program Files\7-Zip\7z.exe" l "FolderName\archive.zip" "file.cmd"') do ...
However, it works if I omit the quotation around the zip-file and the file that is searched.
for /F "delims=" %%a in ('"C:\Program Files\7-Zip\7z.exe" l FolderName\archive.zip file.cmd') do ...
Finally I found a solution to put the command in a variable and place it into the for loop.
set command="C:\Program Files\7-Zip\7z.exe" l "FolderName\archive.zip" "file.cmd"
for /F "delims=" %%a in ('"%command%"') do ...
The variable still requires quotation marks. I'd like to understand how that works. How can I have multiple quoted strings that are placed in a quoted variable but cannot pass them directly to the for loop.
It seems to be a similar problem as the operators like &, >, |, ... that need escaping with ^. I tried that too, but with no success. It kept me asking: "more?" thus the closing bracket wasn't found anymore.
CodePudding user response:
Well, you actually answered your own question without looking closely. Let me show you why:
set command="C:\Program Files\7-Zip\7z.exe" l "FolderName\archive.zip" "file.cmd"
for /F "delims=" %%a in ('"%command%"') do ...
Note that your code translates the value of the set
command to:
"C:\Program Files\7-Zip\7z.exe" l "FolderName\archive.zip" "file.cmd"
where you then pass that to the loop in double quotes again, as:
"%command%"
which ends up being:
""C:\Program Files\7-Zip\7z.exe" l "FolderName\archive.zip" "file.cmd""
Which will work exactly in a for loop:
for /f "delims=" %%i in ('""C:\Program Files\7-Zip\7z.exe" l "FolderName\archive.zip" "file.cmd""') do ...
Though that will work as expected in this case, it will fail if your quoted strings contain special characters like &
as shown in this example:
for /f "delims=" %%i in ('""C:\Program Files\7-Zip\7z.exe" l "FolderName\archives & backups.zip" "file.cmd""') do ...
So you need to simply escape the outer double quotes to overcome this:
for /f "delims=" %%i in ('^""C:\Program Files\7-Zip\7z.exe" l "FolderName\archives & backups.zip" "file.cmd"^"') do ...
Point 2. from cmd /?
seemingly states this behaviour, as per the below screenshot: