代码之家  ›  专栏  ›  技术社区  ›  Garret Wilson

引用可能以反斜杠结尾的Windows批处理参数

  •  1
  • Garret Wilson  · 技术社区  · 7 年前

    假设我想打电话给Robocopy复制 *.foo A:\ B:\

    robocopy A:\ B:\ *.foo
    

    %~1

    robocopy "%SOURCE%" B:\ *.foo
    

    不幸的是,如果 %SOURCE% \ "

    robocopy "A:\" B:\ *.foo
    

    所以Windows认为第一个参数是 "A:" B:\ *.foo

    我怎样才能关掉对 \"

    2 回复  |  直到 7 年前
        1
  •  0
  •   undo    7 年前

    \\ \ ,第一个反斜杠逸出第二个,再也没有任何内容逸出。

    <command> "this\is\a\path\\" "\this\is\another\path\\"
    

    robocopy

    robocopy "this\is\a\path" "this\is\another\path" <args>
    

    %SOURCE%=%SOURCE:\=\\% 
    

    之后,您可以使用 %SOURCE%

        2
  •  0
  •   Mofi    7 年前

    我建议使用像这样的批处理文件:

    @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 /?
    推荐文章