PSA: checking errorlevel for Windows jobs with and without EnableDelayedExpansion

Discussion created by Carsten_Schmitz on Dec 8, 2017
Latest reply on Dec 11, 2017 by Carsten_Schmitz
To whom it may concern, some pointers on error handling in Windows jobs.

  1. This may be known to many, but since I have ignored this myself for some time, I reiterate:

    Automic Windows jobs need to have the following lines of code aftereach and every statement that can possibly fail:

      @set retcode=%errorlevel%
      @if NOT %ERRORLEVEL% == 0 goto :retcode

    What this does is check the return code, and if an error occurs, jump to the label called :retcode. That label does NOT need to be defined, it is automatically appended by Automic when the job is generated. You can see it's content by clicking "open generated job" in the activity window. It calls the "Job Messenger" (basically calls the agent .exe) and tells it to report the error code back to UC4. Without these lines, your job will always be ENDED_OK, no matter what.

  2. One of our users dutifully had these lines, but his job still was "ENDED_OK" even when an error happens. Why? He was using a special construct:setlocal EnableDelayedExpansionas part of his Windows cmd.exe batch file, called from Automic.

    setlocal EnableDelayedExpansionis probably the dirtiest hack I have seen come out of Redmond for a long time  :)  It works arround a limitation of variable expansion in cmd.exe, where variables assignment does not work as expected in compound statements, such asifblocks. To work arround this, it introduces another meta layer to the cmd.exe interpreter, which as a side effect also changes thesyntax of variables. The%variable%-style syntax turns into a!variable!-style syntax. A goodexample of why this may be needed is found here.

    When you're working withEnableDelayedGratificat^h^h^w, erm I mean EnableDelayedExpansion active, then you need to change your Automic-supplied lines as well, to this:

      @set retcode=!errorlevel!
      @if NOT !ERRORLEVEL! == 0 goto :retcode

    Only then will your errorlevel checking work properly (at least on the Windows server we tried this on. As per the documentation, the percent sign syntaxshould have still worked, but alas, it demonstratably didnot).

  3. Somewhat unrelated, please note that %errorlevel% and is itself fraught with unintuitive issues, and also possibly handled differently in different versions of Windows. For one thing, there is an %errorlevel% variable and anerrorlevel function, and the later compares %errorlevel% to the argument given,or greater. But that's just a heads-up as an aside, that has nothing to do with AE/UC4 specificially.
Hope this helps.