windowsbatch-filecmderrorlevel

Batch File: Variable being resolved in set command, before I call it


I want to create a logging system: Add %Logger% after a command to get logs. With only error output, error count.

I want it go get %Errorlevel% from the previous program when i call %Logger% (EG: I want to get %Errorlevel% from del nul when i run del nul %Logger%) I have this code:

Set Logger=2^>CurrentError.log ^>^>%LogName% ^& set Err=%Errorlevel% ^& (for /f "tokens=*" %%a in (CurrentError.log) do (echo [EROR] %%a) ^>^> ErrorConsole.log) ^& (if exist ErrorConsole.log type ErrorConsole.log) ^& type CurrentError.log ^>^>%LogName% ^& (if exist ErrorConsole.log del ErrorConsole.log) ^& (if %Err% GTR 0 set /a ErrNum=ErrNum+1 ^>nul ^& echo %ESC%[33m[WARN] An error has occurred, installation will continue.%ESC%[91m)

When i run the code, %Errorlevel% is already resolved as it's value in %Logger%.

If i use %%Errorlevel%%, %Errorlevel% is not solved but when i call %Logger%, %Errorlevel% is a string, not being resolved as it's value (%Errorlevel% still %Errorlevel%, not 0 or 1)


Solution

  • @echo off
    setlocal enabledelayedexpansion
    
    set "ESC="
    set "ErrNum=0"
    set "LogName=Stdout.log"
    
    set Logger=2^>CurrentError.log ^>^> "%LogName%" ^&^
     set "Err=^!Errorlevel^!" ^&^
     (for /f "tokens=*" %%a in (CurrentError.log) do echo [EROR] %%a) ^>^> ErrorConsole.log ^&^
     (if exist ErrorConsole.log type ErrorConsole.log) ^&^
     type CurrentError.log ^>^> "%LogName%" ^&^
     (if exist ErrorConsole.log del ErrorConsole.log) ^&^
     (if ^^!Err^^! NEQ 0 set /a "ErrNum+=1" ^& echo %ESC%[33m[WARN] An error has occurred, installation will continue.%ESC%[91m)
    
    del nul %Logger%
    pause
    

    The value of ESC may not display though it does exist.

    Delayed expansion used as the logger variable, with code as value is to be used on the same line as the command. Delayed expansion variables use syntax !name! instead of %name%.

    ^ used at end of lines to continue to next line. set Logger=... viewed easier over multiple lines.

    ! escaped as needed i.e. ^! if within a string, else ^^!.

    Changed set /a ErrNum=ErrNum+1 to equivalent set /a "ErrNum+=1".