我需要在 Windows 10 批处理文件中引用任意参数,当它们以反斜杠结尾时我遇到了问题。
假设我想调用 Robocopy 将
*.foo
文件从 A:\
复制到 B:\
,如下所示:
robocopy A:\ B:\ *.foo
但实际上我得到了
A:\
作为参数(假设我使用 %~1
,并且我不知道它是否包含空格,所以我引用它:
robocopy "%SOURCE%" B:\ *.foo
不幸的是,如果
%SOURCE%
以反斜杠结尾,则最后一个 \
被视为转义字符,转义 "
。
robocopy "A:\" B:\ *.foo
因此 Windows 认为第一个参数是
"A:" B:\ *.foo
。
如何关闭将
\"
解释为转义序列?
很简单!你需要转义转义字符!当您使用
\\
而不是 \
时,第一个反斜杠会转义第二个反斜杠,并且不会再转义任何内容。
因此,在运行命令时,您应该使用以下命令:
<command> "this\is\a\path\\" "\this\is\another\path\\"
即使你不以反斜杠结束路径,
robocopy
也能工作,这也是毫无价值的。所以你也完全可以使用这个:
robocopy "this\is\a\path" "this\is\another\path" <args>
如果您不知道路径是否以反斜杠结尾(例如,如果您从用户处获取路径),则可以使用此命令转义路径中的所有反斜杠:
%SOURCE%=%SOURCE:\=\\%
之后,您可以使用
%SOURCE%
作为参数正常运行 robocopy,即使它以反斜杠结尾!
我建议使用像这样评论的批处理文件:
@echo off
if not exist %SystemRoot%\System32\robocopy.exe goto BatchHelp
if "%~1" == "" goto BatchHelp
if "%~1" == "/?" goto BatchHelp
if "%~2" == "" goto BatchHelp
call :CleanPath SOURCE %1
call :CleanPath DESTINATION %2
%SystemRoot%\System32\robocopy.exe "%SOURCE%" "%DESTINATION%" *.foo
rem Delete the used environment variables.
set "SOURCE="
set "DESTINATION="
rem Avoid a fall through to the subroutine CleanPath.
exit /B
rem The subroutine CleanPath must be called with two arguments.
rem The first one must be the environment variable which should hold the
rem cleaned folder path for usage with ROBOCOPY. The second argument must
rem be the folder path which should be cleaned for usage with ROBOCOPY.
:CleanPath
rem Get full absolute path of folder path. This reduces a lot of variants
rem which could occur on batch file called with various relative paths.
set "FolderPath=%~f2"
rem Does the folder path not end with a backslash?
if not "%FolderPath:~-1%" == "\" goto HavePath
rem Does the folder path have just three characters and is ending with
rem a colon and a backslash? Yes, append an escaping backslash at end.
rem Otherwise the folder path of a folder not being the root folder
rem of a drive ends with a backslash which must be removed to get
rem the folder path correct interpreted by ROBOCOPY.
if "%FolderPath:~1%" == ":\" (
set "FolderPath=%FolderPath%\"
) else (
set "FolderPath=%FolderPath:~0,-1%"
)
:HavePath
set "%~1=%FolderPath%"
set "FolderPath="
rem Return to calling routine.
goto :EOF
:BatchHelp
cls
echo Usage: %~nx0 source destination
echo(
echo source ... source directory
echo destination ... destination directory
echo(
echo This batch file requires ROBOCOPY in Windows system directory.
echo(
pause
要了解所使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完整、仔细地阅读每个命令显示的帮助页面。
call /?
cls /?
echo /?
exit /?
goto /?
if /?
pause /?
rem /?
robocopy /?
set /?