我需要在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
。
如何关闭将\"
解释为转义序列?
答案 0 :(得分:0)
很简单!您需要逃脱转义字符!当您使用\\
而不是\
时,第一个反斜杠会转义第二个反斜杠,并且不会再转义。
因此,在运行命令时,应使用以下命令:
<command> "this\is\a\path\\" "\this\is\another\path\\"
即使您不使用反斜杠结束路径,robocopy
的工作也毫无意义。因此,您也可以完全使用以下代码:
robocopy "this\is\a\path" "this\is\another\path" <args>
如果您不知道路径是否以反斜杠结尾(例如,如果从用户那里获取),则可以使用此命令来转义路径中的所有反斜杠:
%SOURCE%=%SOURCE:\=\\%
此后,即使它以反斜杠结尾,也可以使用%SOURCE%
作为参数正常运行robocopy!
答案 1 :(得分:0)
我建议使用这样的批处理文件:
@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.
goto :EOF
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 /?
goto /?
if /?
pause /?
rem /?
robocopy /?
set /?