How to determine if I'm in powershell or cmd?
All credit goes to PetSerAl, this had to be posted as an aswer:
(dir 2>&1 *`|echo CMD);&<# rem #>echo PowerShell
Within Win32-OpenSSH
this command also works, and outputs CMD
.
NB : Win32-OpenSSH
seems a bit limited, cd
is not recognized on my system.
I'd like to expand on @sodawillow's answer to also distinguish between using Powershell (powershell.exe) known as Desktop
and PWSH (pwsh.exe) known as Core
.
(dir 2>&1 *`|echo CMD);&<# rem #>echo ($PSVersionTable).PSEdition# Returns one of: CMD, Core, Desktop
This works in all instances where a sub-shell is not instantiated. What that means is that it does not work from opening a default sub-process in Python, as it always uses CMD when interacting with windows. This is actually set by the Windows environment variable: ComSpec
always pointing to C:\Windows\system32\cmd.exe
.
For example:
(Starting the python interpreter from a pwsh shell.)
>>> import os, subprocess>>> c="(dir 2>&1 *`|echo CMD);&<# rem #>echo($PSVersionTable).PSEdition">>> subprocess.call(c,shell=True)CMD
For other Python shell detection schemes, please see this good post.
UPDATE: 2020-05-01
I managed to get the above working, but with the obnoxious side effect of always loading the powershell profile, before executing. The trick was to specify execute=<path-to-powershell-exe>
like this:
(Start a python CLI.)
import os, subprocessc="(dir 2>&1 *`|echo CMD);&<# rem #>echo($PSVersionTable).PSEdition"e="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"subprocess.call(c, shell=True, executable=e)# output:# <blah blah from profile># Desktop# 0
I have not been able to circumvent the powershell profile issue. But apparently it is something being worked on. See here and here.