for-loopbatch-filecolorschaining

Color encoding breaking for ECHO command inside FOR command but only if there is a second command inside


Im writing a script to automatially import all .reg files in %bkps% but i would like a custom success message instead of the orriginal "Operation completed successfully." This is my code; (NOTE '{ESC}' I'm using to denote the invisible ESC character)

(for /f "tokens=*" %%f in ('dir %bkps% /b /o:gd /a-d') do (
    reg import "%bkps%\%%f" 2>NUL && echo {ESC}[37m│ ├─{ESC}[30m{ESC}[42m%%f was successfully restored.{ESC}[40m
))

and when its run in my program i get the output;

←[37m│ ├─←[30m←[42mFontBKP_partA133200.reg was successfully restored.←[40m
←[37m│ ├─←[30m←[42mFontBKP_partB133200.reg was successfully restored.←[40m

it should look like this with the colors added;

│ ├─FontBKP_partA133200.reg was successfully restored.
│ ├─FontBKP_partB133200.reg was successfully restored.

The echo command works elsewhere in the code and even works on its own inside the FOR loop but as soon as it goes inside that FOR loop with the reg command it is printed literally without the colors. (i tried it with the && and on a whole new line running non-conditionally, no luck)

some other threads about this are here but i am not sure if i can apply any of their to my code as i need it to run conditionally off the import command and it needs to run an indefinite amount of times (although it should never be more than like 25)

How to echo with different colors in the Windows command line INSIDE A FOR LOOP WITH A CHOICE cmd

Batch script : issue with colored echo when chaining commands

Cmd.exe Batch Script Color Output With FOR /F 'MSYS' Commands


Solution

  • Ok i found a solution using this fix; https://stackoverflow.com/a/60865920/21768379

    I changed my code from

    (for /f "tokens=*" %%f in ('dir %bkps% /b /o:gd /a-d') do (
        reg import "%bkps%\%%f" 2>NUL && echo {ESC}[37m│ ├─{ESC}[30m{ESC}[42m%%f was successfully restored.{ESC}[40m
    ))
    

    to

    (for /f "tokens=*" %%f in ('dir %bkps% /b /o:gd /a-d') do (
        reg import "%bkps%\%%f" 2>NUL && echo success | (findstr /R success) & echo {ESC}[37m│ ├─{ESC}[30m{ESC}[42m%%f was successfully restored.{ESC}[40m
    ))
    

    and now it outputs with the correct colors (albeit with the extra line that says "success" before it but I can figure that out later)

    Edit: It was as simple as adding >NUL to the first echo command like this;

    (for /f "tokens=*" %%f in ('dir %bkps% /b /o:gd /a-d') do (
            reg import "%bkps%\%%f" 2>NUL && echo success >NUL | (findstr /R success) & echo {ESC}[37m│ ├─{ESC}[30m{ESC}[42m%%f was successfully restored.{ESC}[40m
    ))