我想对上述解决方案补充一点:
如果在路径中找到您的命令,或者如果命令是没有空格或特殊字符的 cmdpath,则所有这些语法都可以很好地工作。
但是,如果您尝试使用位于路径包含特殊字符的文件夹中的可执行命令,则需要将命令路径用双引号 (") 括起来,然后 FOR /F 语法不起作用。
例子:
$ for /f "tokens=* USEBACKQ" %f in (
`""F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" Hello '"F:\GLW7\Distrib\System\Shells and scripting"'`
) do echo %f
The filename, directory name, or volume label syntax is incorrect.
或
$ for /f "tokens=* USEBACKQ" %f in (
`"F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe" "Hello World" "F:\GLW7\Distrib\System\Shells and scripting"`
) do echo %f
'F:\GLW7\Distrib\System\Shells' is not recognized as an internal or external command, operable program or batch file.
或
`$ for /f "tokens=* USEBACKQ" %f in (
`""F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" "Hello World" "F:\GLW7\Distrib\System\Shells and scripting"`
) do echo %f
'"F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" "Hello' is not recognized as an internal or external command, operable program or batch file.
在这种情况下,我发现使用命令并将其结果存储在变量中的唯一解决方案是将(临时)默认目录设置为命令本身:
pushd "%~d0%~p0"
FOR /F "tokens=* USEBACKQ" %%F IN (
`FOLDERBROWSE "Hello world!" "F:\GLW7\Distrib\System\Layouts (print,display...)"`
) DO (SET MyFolder=%%F)
popd
echo My selected folder: %MyFolder%
那么结果就是正确的:
My selected folder: F:\GLW7\Distrib\System\OS install, recovery, VM\
Press any key to continue . . .
当然,在上面的示例中,我假设我的批处理脚本与我的可执行命令之一位于同一文件夹中,以便我可以使用“%~d0%~p0”语法。如果这不是您的情况,那么您必须找到一种方法来定位您的命令路径并将默认目录更改为它的路径。
注意:对于那些想知道的人,这里使用的示例命令(选择文件夹)是 FOLDERBROWSE.EXE。我在网站 f2ko.de (http://f2ko.de/en/cmd.php) 上找到了它。
如果有人对通过复杂路径访问的那种命令有更好的解决方案,我会很高兴听到它。
吉尔