如何确定我是在 powershell 中还是在 cmd 中?

How to determine if I'm in powershell or cmd?

我一直在玩 OpenSSH on Windows,看起来正常的 Unix 别名丢失了。当我通过 SSH 登录 Windows 机器时,我不确定它是启动 powershell 还是 cmd。在 Windows 上查看当前 运行 shell 的正确方法是什么?

所有功劳归于PetSerAl,这必须作为答案发布:

(dir 2>&1 *`|echo CMD);&<# rem #>echo PowerShell

Win32-OpenSSH 中此命令也有效,并输出 CMD

注意:Win32-OpenSSH 似乎有点受限,cd 在我的系统上无法识别。

我想扩展@sodawillow 的回答以区分使用 Powershell (powershell.exe) 称为 DesktopPWSH (pwsh.exe) 称为 Core

(dir 2>&1 *`|echo CMD);&<# rem #>echo ($PSVersionTable).PSEdition
# Returns one of: CMD, Core, Desktop

这适用于子shell 实例化的所有实例。这意味着在 Python 中打开默认子进程 不起作用 ,因为它在交互时总是使用 CMD windows。这实际上是由 Windows 环境变量设置的:ComSpec 始终指向 C:\Windows\system32\cmd.exe.

例如:

(从 pwsh shell 启动 python 解释器。)

>>> import os, subprocess
>>> c="(dir 2>&1 *`|echo CMD);&<# rem #>echo($PSVersionTable).PSEdition"
>>> subprocess.call(c,shell=True)
CMD

其他Pythonshell检测方案请见


更新:2020-05-01

我设法使上述工作正常,但令人讨厌的副作用是 总是 加载电源shell 配置文件 , 在执行之前。诀窍是像这样指定 execute=<path-to-powershell-exe>

(启动 python CLI。)

import os, subprocess
c="(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

我无法绕过电源shell 配置文件问题。但是 it is something being worked on. See here and here