我有 Windows 批处理脚本
calculate.bat
,如下所示:
@echo on
REM check if the user has provided the expected number of arguments
if "%~2"=="" (
echo Usage: %0 ^<directory location of dll files^> ^<directory location of calculate executable^>
exit /b 1
)
set "search_dir=%~1"
set "calc_path=%~2"
cd C:\tmp\xyz.d\
if exist checksum_file (
del checksum_file
)
set "calc_exe=%calc_path%\calc.exe"
REM iterate over all .dll files in the search directory
for %%I in ("%search_dir%\*.dll") do (
REM #working with calc_exe path without spaces,but does not work with path having spaces
for /F %%A in ('%calc_exe% "%%I"') do echo %%I %%A >> checksum_file
)
如果传递的第二个参数的路径没有空格,则它可以工作
"C:\Working\test\bin"
。
例如:
calculate.bat "C:\Program Files\test\Windows-x86-64" "C:\Working\test\bin"
但是如果我用空格传递第二个参数的路径
"C:\Program Files\test\bin"
:
例如:
calculate.bat "C:\Program Files\test\Windows-x86-64" "C:\Working\test\bin"
它不起作用并给出如下错误:
for /F %A in ('C:\Program Files\test\bin\calc.exe "C:\Program Files\test\Windows-x86-64\sample.dll"') do echo C:\Program Files\test\Windows-x86-64\sample.dll %A 1>>checksum_file
)
'C:\Program' is not recognized as an internal or external command,
operable program or batch file.
这是直到第一次出现空格为止的考虑路径。
您面临的问题是因为批处理脚本中的
for /F
循环将空格分隔的值视为单独的标记。因此,当您传递带有空格 (C:\Program Files\test\bin
) 的路径时,它会将 C:\Program
和 Files\test\bin
视为两个令牌并尝试执行它们(一个接一个),从而导致您看到的错误。
@echo on
REM check if the user has provided the expected number of arguments
if "%~2"=="" (
echo Usage: %0 ^<directory location of dll files^> ^<directory location of calculate executable^>
exit /b 1
)
set "search_dir=%~1"
set "calc_path=%~2"
cd C:\tmp\xyz.d\
if exist checksum_file (
del checksum_file
)
set "calc_exe=%calc_path%\calc.exe"
REM iterate over all .dll files in the search directory
for %%I in ("%search_dir%\*.dll") do (
REM #working with calc_exe path with spaces
for /F %%A in ('"%calc_exe%" "%%I"') do echo %%I %%A >> checksum_file
)
通过在 for /F 循环中将
%calc_exe%
括在双引号内,整个路径将被视为单个标记,并且脚本将正确处理包含空格的路径。
现在,您可以像这样执行批处理脚本:
calculate.bat "C:\Program Files\test\Windows-x86-64" "C:\Working\test\bin"