开发者

Batch File: FOR /F doesn't work if path has spaces

This is the problem I'm having:

@ECHO OFF

REM If this batch file is run in the same directory as "command.exe" then the
REM following line will work.
FOR /F "usebackq" %%A IN (`command.exe "C:\File Being Passed as a Parameter.txt"`) DO ECHO %%A

REM The following line does not work no matter where this batch file is run.
FOR /F "usebackq" %%A IN (`"C:\Folder With Spaces\command.exe" "C:\File Being Passed as a Parameter.txt"`开发者_开发问答) DO ECHO %%A

I would like to store this batch file wherever I want and not be forced to store it in the same folder as command.exe. Any suggestions?


Add CALL before the program name:

FOR /F "usebackq" %%A IN (`CALL "C:\Folder With Spaces\command.exe" "C:\File Being Passed as a Parameter.txt"`) DO ECHO %%A


The call trick of Andriy M is clever and works fine, but I tried to understand the problem here.

This problem is caused by the cmd.exe, as you can read at cmd /help

....
the first and the last quote will be removed, when there are not exactly two quotes in the line.
...

So there is also another solution with simply adding two extra quotes

FOR /F "usebackq=" %%A IN (`""C:\Folder Space\myCmd.exe" "Param space""`) DO (
    ECHO %%A
)


Careful:

Using 'call' (as shown by Andriy M) seems the safest option.

I found a case where adding leading and trailing double quotes (as suggested as a possible solution by jeb) has a problem.

Problem:

for /f "delims=" %%i in ('""C:\path with spaces\hello.bat" "filename with an & ampersand.jpg""') do ( echo output=%%i )

cmd.exe's output: & was unexpected at this time.

Solution:

for /f "delims=" %%i in ('call "C:\path with spaces\hello.bat" "filename with an & ampersand.jpg"') do ( echo output=%%i )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜