Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recognize the new Windows Terminal from a PowerShell script

I'm writing a new PowerShell script, and I want to make use of unicode emojies, which are now supported by the new Windows Terminal Preview. However, for a user running "legacy" PowerShell that doesn't support it, I do not wish to show the unrecognized characters, and instead I would like to show him some other text/sign.

To be more simple - I would like to know when my PS script is running in the new Terminal and show one thing and show something else for other PS terminals.

I have tried using $env:TERM_PROGRAM. If I use is inside the vscode PS terminal it returns "vscode", but under normal PS terminal or new terminal it returns nothing.

Any ideas?

like image 914
developer82 Avatar asked Aug 05 '19 15:08

developer82


People also ask

How do I find out what version of Windows Terminal I have?

Checking your Windows version using CMD Press [Windows] key + [R] to open the “Run” dialog box. Enter cmd and click [OK] to open Windows Command Prompt. Type systeminfo in the command line and hit [Enter] to execute the command.

How do I use the new Terminal in Windows?

Invoke the command palette You can invoke most features of Windows Terminal through the command palette. The default key combination to invoke it is Ctrl + Shift + P . You can also open it using the Command palette button in the dropdown menu in Windows Terminal Preview.

How do I get to the Terminal in PowerShell?

From the Start MenuClick Start, type PowerShell, and then click Windows PowerShell. From the Start menu, click Start, click All Programs, click Accessories, click the Windows PowerShell folder, and then click Windows PowerShell.

Is Windows Terminal different from PowerShell?

Windows Terminal allows you to run Bash and other command-line utilities, including PowerShell. It also supports more characters, has a fancy new text rendering engine, and allows you to customize its appearance.


2 Answers

Windows Terminal is still in its infancy and not much to go by to identify it but I noticed that it adds an environment variable WT_SESSION, you might try checking for that:

if ($env:WT_SESSION) {
     "I am in Windows Terminal"
} else {
     "Nothing to see here..."
}
like image 175
Adil Hindistan Avatar answered Sep 23 '22 17:09

Adil Hindistan


An alternative to the other answer without dependency on environment, you can check the process parent stack for the Terminal executable:

$isTerminal = {
    $p = Get-CimInstance -ClassName Win32_Process -Filter ProcessID=$PID
    while ($p) {
        ($p = Get-CimInstance -ClassName Win32_Process -Filter ProcessID=$($p.ParentProcessID) -ErrorAction Ignore)
    }
}.Invoke().Name -contains 'WindowsTerminal.exe'

This is a method I've used to determine whether I'm in conemu.

like image 33
Maximilian Burszley Avatar answered Sep 25 '22 17:09

Maximilian Burszley