Windows – Clear Windows Terminal + cmd.exe from .bat file

batch fileterminalwindowswindows-terminal

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.

Best Answer

Just tested this to work in Terminal:

:: Q:\Test\2019\08\29\SO_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%
Related Question