从包含空格的可变path的batch file中调用.exe

我想从batch file启动一个Windows可执行文件,其中可执行文件的path存储在一个variables中。

@echo off set qtpath=C:\Program Files\Qt\5.7\mingw53_32\bin set execpath=%qtpath%\windeployqt.exe echo %execpath% %execpath% --someparams 

不幸的是执行我的脚本会抛出一个错误:

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

看起来不知怎的,string在Program Files的空间被终止。

你应该改变你的代码:

 @echo off set "qtpath=C:\Program Files\Qt\5.7\mingw53_32\bin" set "execpath=%qtpath%\windeployqt.exe" echo "%execpath%" "%execpath%" --someparams 

SPACETAB一样, , =和非间断空格(ASCII 0xFF )在命令提示符cmd构成标记分隔符 。 为了避免令牌化,把你的路径放在""之间。 这也避免了像^()&<>|这样的特殊字符的问题 。

set命令行中的引号再次避免了特殊字符的麻烦; 它们不会成为变量值的一部分,因为它们包含整个赋值表达式。

我建议不要将引号包含在变量值中( set VAR="some value" ),因为那样会遇到问题,特别是在由于不需要的(双引号)引起的字符串连接时(例如, echo "C:\%VAR%\file.txt"返回"C:\"some value"\file.txt" )。

你是完全正确的。 如果要执行的文件的路径包含空格,则必须用引号括起来:

 @echo off set qtpath=C:\Program Files\Qt\5.7\mingw53_32\bin set execpath="%qtpath%\windeployqt.exe" echo %execpath% %execpath% --someparams 

这应该工作。

当您%execpath%引号括%execpath%时,它也会起作用:

 "%execpath%" --someparams