Using robocopy with Visual Studio 2010 Post-build and Pre-build events

前端 未结 7 2064
忘了有多久
忘了有多久 2021-02-05 01:59

Robocopy outputs 1 upon success, unlike most programs that exit with 0 on success. Visual Studio (and MSBUILD) interprets exit code of 1 as an error.

How can Robocopy b

7条回答
  •  名媛妹妹
    2021-02-05 02:38

    The accepted answer is overkill IMO. Robocopy already has its exit codes defined, so we can usually assume any value of 8 or less indicates things went well.

    "Any value greater than 8 indicates that there was at least one failure during the copy operation."

    So let's say your command is, ROBOCOPY $(Source) $(Dest) *.*, which I'll just refer to as $(RobocopyBinCommand).

    In Visual Studio for your Pre-Build or Post-Build Event, click the dropdown and select

    Create a new line below your command, and place IF %ERRORLEVEL% LEQ 8 EXIT 0 then apply and close the Properties window, eg:

    Advanced Exit Code Requirements

    Let's say you only want the build to pass if ROBOCOPY returns 1 or 3. The if-check above won't allow you to even use the OR-like behavior supported by CMD.exe to fix the issue. You can work around this limitation multiple ways but I think this is one of the most concise ways to do it.

    if %errorlevel% LEQ 3 echo %errorlevel%|findstr "1 3"

    One-Liner Explanation

    Basically, we're piping the result of echoing the errorlevel to findstr which is looking for either a 1 or a 3. We don't have to worry about values that have a 3 or a 1 in them like 23 or 16 because the first evaluation makes sure the value is 3 or less. Once that evaluation passes if it does indeed pass it then pipes the errorlevel to findstr which then compares errorlevel to 1 or 3. If either is detected by findstr, findstr will exit 0, otherwise it will not. If the errorlevel was not 3 or less, errorlevel will remain unchanged and the build task will exit 1 as-usual from using ROBOCOPY.

提交回复
热议问题