如何将变量设置为批处理中包含空格的值

时间:2015-01-13 17:00:13

标签: batch-file windows-8

我有一个Windows 8批处理文件,我试图找到一个命令行应用程序。例如,如果路径中没有空格,则此方法可以正常工作:

for /f %%i in ('where frob.exe 2^>NUL') do set frob=%%i
if [%frob%] == [] (
    @echo frob.exe must be in the path
    goto exit
)

但是,我想要一个更通用的解决方案,即使路径为c:\this is a test\frob.exe也能正常工作。所以,我试过这个:

for /f "tokens=*" %%i in ('where frob.exe 2^>NUL') do set frob=%%i

但是,现在我收到错误is was unexpected at this time.

要使批处理文件正确解释复杂路径,我需要做些什么?

2 个答案:

答案 0 :(得分:0)

for /f "delims="...

默认情况下,标准分隔符(如 Space 被选为“标记分隔符”,默认情况下,只有第一个标记被分配给metavraiable(在您的情况下为%%i

for /?

来自文档提示。

答案 1 :(得分:0)

:: quote the assignment to avoid problems with poison characters
for /f "delims=" %%i in ('where frob.exe 2^>NUL') do set "frob=%%i"

:: quote the value as it can contain spaces
if "%frob%"=="" (
    @echo frob.exe must be in the path
    goto exit
)

我认为您的问题出在if而不是for

相关问题