Windows copy command return codes?

前端 未结 5 504
[愿得一人]
[愿得一人] 2020-12-15 16:43

I would like to test for the success/failure of a copy in a batch file, but I can\'t find any documentation on what if any errorlevel codes are returned. For example

<
5条回答
  •  温柔的废话
    2020-12-15 17:08

    I'd opt for xcopy in this case since the error levels are documented (see xcopy documentation, paraphrased below):

    Exit code  Description
    =========  ===========
        0      Files were copied without error.
        1      No files were found to copy.
        2      The user pressed CTRL+C to terminate xcopy.
        4      Initialization error occurred. There is not
               enough memory or disk space, or you entered
               an invalid drive name or invalid syntax on
               the command line.
        5      Disk write error occurred.
    

    In any case, xcopy is a far more powerful solution. The equivalent documentation for copy does not document the error levels.


    As an aside, you may want to rethink your use of the %errorlevel% variable. It has unexpected results, at least in some versions of Windows, if someone has explicitly done something silly like:

    set errorlevel=22
    

    In those cases, the actual variable will be used rather than grabbing the actual error level. The "normal" way of doing this is (in decreasing order since errorlevel is a "greater than or equal to" check):

    if errorlevel 2 (
        echo Copy x y failed due to reason 2
        exit /B
    
    )
    if errorlevel 1 (
        echo Copy x y failed due to reason 1
        exit /B
    )
    

    In addition, if you are running Win7 or Win Server 2008 or later, you should look into Robocopy, which is now the preferred mass-copy solution.

提交回复
热议问题