如何根据当前 运行 终端有条件地在 PowerShell 配置文件中导入模块?

How to conditionally import modules in PowerShell profile based on the currently running terminal?

我只想在从 Windows Terminal 启动 PowerShell 时导入一些模块(posh-git、oh-my-posh 等)。使用 conhost 或从 Cmder 启动 PowerShell 时,应排除这些导入。

但是当我从 Windows 终端或 conhost 或 Cmder 打开 PowerShell 时,我可以看到 $profile 指向同一个文件。

有没有一种方法可以识别当前正在使用的终端,以便我可以在我的 $profile 文件中执行类似的操作?

If ($TERM -eq 'WT') {
    Import-Module posh-git
    Import-Module oh-my-posh
} 

您可以使用自动变量 WSLENVWT_PROFILE_IDWT_SESSION 之一来检查 Powershell 是否在 Windows 终端中运行。它们在“standalone”Powershell 中不存在。

例如:

function Test-IsWindowsTerminal { [bool]($env:WT_Session)}