developer82
developer82

Reputation: 13733

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?

Upvotes: 6

Views: 621

Answers (3)

Gilles Maisonneuve
Gilles Maisonneuve

Reputation: 133

Under CMD:

IF DEFINED ConEmuHWND ECHO This is a ConEmu console.
IF [%ConEmuANSI%]==[ON] ECHO This ConEmu console has ANSI enabled.
IF DEFINED WT_SESSION ECHO This is a Windows Terminal.
IF [%TERM_PROGRAM%]==[Tabby] ECHO This is a Tabby console.

Note: Tabby is normally always ANSI enabled. ConEmu can disable ANSI in settings.

Under ZSH:

if [[ "$ConEmuBackHWND" != "" && $TERM =~ '^xterm' ]]; then echo This is a ConEmu Xterm.; fi

I do not have zsh under Windows Terminal nor Tabby but I assume environment variables $WT_SESSION and $TERM_PROGRAM are similarly defined. It's yours to test.

Upvotes: 0

Maximilian Burszley
Maximilian Burszley

Reputation: 19694

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.

Upvotes: 3

Adil Hindistan
Adil Hindistan

Reputation: 6635

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..."
}

Upvotes: 8

Related Questions