Sitemap
Simian

Simian

How to force a .bat to run in a legacy screen environment of cmd in Windows 11 instead the new Windows Terminal

3 min readMar 29, 2024

Recently i need to run (automatically, called from other software) an old .bat in windows 11.
But this .bat is full of

mode con: cols=XX lines=YY

And the windows 11 terminal does not allow this, the .bat brokes when runs in a standard size of cmd window.
Or i rewrite this old .bat or a give a way to run in a old windows cmd window.
I think the second option is simplest, but how?

No native way to autodetect and change the terminal environment, let’s do this.

This 4 lines script does this, only put this in the header of desired .bat and this detects if the process is running in a new WindowsTerminal or a legacy cmd, when is in a new terminal, it’s start the bat in an instance of old cmd.exe and close the current terminal:

set id=%random%
title %id%
tasklist /v /fo csv | findstr "%id%" | findstr "cmd.exe"
if %errorlevel% == 1 start conhost "%~f0" & GOTO :EOF

But How This works?

The first line:
Gets an random number to the ID variable, random numbers allow you to run multiple instances without conflicting.

Get Simian’s stories in your inbox

Join Medium for free to get updates from this writer.

The second line:
We set the title of terminal tab as the random number in the ID variable, we use this before…

In the third line:
We do a lot of things…
A) Lists all running process with window name, PID and host executable name in csv format
|
B) Filters “A” step result for processes that have the window name equal to ID variable
|
C) Filters the result of “B” step for processes that have a host executable called cmd.exe

Brief explaination: The new windows terminal host have an executable name called “WindowsTerminal.exe”

The classic windows terminal host have the executable called “CMD.EXE”.

The C step results in an boolean ErrorLevel value where 0 is for TRUE and 1 is for FALSE (yes in reverse way)

In sume this catch the running process that where the window name is equal to the ID variable (terminal tab name) and if is true that is running in a legacy “cmd.exe” as his host this results in a 0 value for the errorlevel, else (not running in a cmd.exe as host) results in a 1 value for the errorlevel.

The Fourth line:
Is a simple if statement that use the errorlevel resultant of the 3rd line.
If the errorlevel is 1, start the command conhost “%~f0” and goes to End Of File (exit)
Else, does nothig it continues running the rest of the script.

The command conhost “%~f0” calls the system executable called conhost.exe and instruct this to run an old cmd.exe running the .bat contained in the variable %~f0
The variable %~f0 is containing the full path of current .bat and his name like C:\Bat\folder\name.bat and is declared automatically by the terminal environment.

--

--