microsoft / terminal

The new Windows Terminal and the original Windows console host, all in the same place!
MIT License
95.27k stars 8.27k forks source link

How can I determine if my PowerShell script is running in Windows terminal? #6269

Closed kasini3000 closed 4 years ago

kasini3000 commented 4 years ago

How can I determine if my PowerShell script is running in Windows terminal?

I wrote a script, a.ps1, which contains some special unicode characters. I want to check whether my script is running in the powershell executed by windows terminal. How can I detect the windows terminal host?

marvhen commented 4 years ago

This is working for me:

#Is-WindowsTerminal.ps1

function IsWindowsTerminal ($childProcess) {
    if (!$childProcess) {
        return $false
    } elseif ($childProcess.ProcessName -eq 'WindowsTerminal') {
        return $true
    } else {
        return IsWindowsTerminal -childProcess $childProcess.Parent
    }
}

return IsWindowsTerminal -childProcess (Get-Process -Id $PID)
kasini3000 commented 4 years ago

Great,3q alot!

oising commented 4 years ago

@kasini3000 @marvhen I think it's considerably easier to check for the existence of the WT_SESSION environment variable.

function Test-WindowsTerminal { test-path env:WT_SESSION }

# or

if ($env:WT_SESSION) { 
    # yes, windows terminal
} else {
    # nope
}
marvhen commented 4 years ago

Indeed...much easier. I was not aware of that variable, but now see it is documented here.

titoaldarondo commented 3 years ago

So I too initially headed down the route of checking $Env:WT_SESSION, but quickly realized that this wouldn't work when SSHing to other hosts. Instead, I decided to simply check for Unicode support in the current session:

function Test-IsEmojiFriendly {
  if ("$OutputEncoding".EndsWith('UTF8Encoding')) {
    return $true
  }
  return $false
}

There are probably other terminal-specific considerations here, but hopefully this helps.

DHowett commented 3 years ago

That's just going to tell you if PowerShell thinks it can send UTF-8 data somewhere; it will not tell you anything about the capabilities of the terminal it's talking to.

gerardog commented 2 years ago

FYI. I just rewrote IsWindowsTerminal but with support for WT as default terminal app, in this comment.

mrkey7 commented 5 months ago

function IsWTrun {'WindowsTerminal' -in (Get-Process).Name}

gerardog commented 5 months ago

function IsWTrun {'WindowsTerminal' -in (Get-Process).Name}

That returns true if any instance of WindowsTerminal is running. PowerShell could be running on an old Console Host and still return true if a WT is open.

mrkey7 commented 5 months ago

function IsWTrun {'WindowsTerminal' -in (Get-Process).Name}

That returns true if any instance of WindowsTerminal is running. PowerShell could be running on an old Console Host and still return true if a WT is open.

Thanks. Do you have a 100% valid method? Looking for $Env:WT_SESSION not valid too