Clear Windows Terminal + cmd.exe from .bat file

Posted on

QUESTION :

I am using Windows Terminal along with a batch file that runs cls as the first command. Under standalone cmd.exe running cls clears the window and scrollback. Under Windows Terminal, it does not clear the scrollback.

What can I add to my .bat file along with cls to remove the scrollback?

This bug report claims that using echo "$([char]27)[2J$([char]27)[3J" clears the scrollback, but I believe that this applies to either Ubuntu host or Powershell. If I put that command verbatim into the .bat file it just echoes those literal characters.

ANSWER :

Just tested this to work in Terminal:

:: Q:Test2019829SO_1476288.cmd
:: Since windows 10 Treshold2 the console understands  
:: [Ansi Escape Codes](https://en.wikipedia.org/wiki/ANSI_escape_code)  
:: These codes require the escape char hex 0x1b or decimal 27 which is  
:: difficult to generate (depends on your editor)  
::  
::     esc [ 2  J  esc [ 3  J
:: hex 1B 5B 32 4A 1B 5B 33 4A
::
:: This Batch uses certutil to decode a hex string to ascii here
@echo off
echo 1B 5B 32 4A 1B 5B 33 4A>Clear.hex
Del Clear.bin
certutil -decodehex Clear.hex Clear.bin >NUL 2>&1
Set /P Clear=<Clear.bin

dir
Timeout /t 3 >Nul
Echo %Clear%

Per the comments by @LotPings you can do this if you can type an ASCII escape character (code 27) into your batch file.

@cls && echo ā›[2Jā›[3J

That is what $([char]27) was doing in my original question. Unfortunately, most web browsers will strip these if I paste them in a code block. The ā› character seen above is not ASCII 27, but indicates where that character needs to be.

If you can run this JavaScript code, you can copy the result and paste into a .bat file.

alert("@cls && echo "+String.fromCharCode(27,91,50,74,27,91,51,75))

Leave a Reply

Your email address will not be published. Required fields are marked *