PowerShell ISE 无法识别 $profile 变量

PowerShell ISE not recognizing $profile variables

在我的 $profile 目录中,我有一些自定义变量,以及默认变量,例如 $root ( 等于 "C:\") 等。我有一个自定义变量保存我桌面的文件路径,因此我可以轻松引用该路径,而且不必每次都创建变量我启动的时间 PS。如果我尝试解析 $profile 路径中的任何变量值 ISE 脚本窗格和控制台 ) 它不起作用。但是,如果我使用常规的 PS 终端,它就没有问题。有什么建议或解释吗?

$profile 在 ISE 中不同:

$profile
C:\Users\js\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

控制台:

$profile
C:\Users\js\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

PowerShell ISE 使用与标准 PowerShell 会话不同的主机配置文件。 $profile变量实际上默认显示的是CurrentUserCurrentHost配置文件,但是加载PowerShell时默认有four profile locations stored in this variable. Each of these locations are dot-sourced。您可以通过键入 $profile | Get-Member -MemberType NoteProperty 来查看已配置的配置文件总数:

  • AllUsersAllHosts
  • AllUsersCurrentHost
  • CurrentUserAllHosts
  • 当前用户当前主机

在我们继续之前,让我们先谈谈什么是 PowerShell 主机。来自 Microsoft:

The host application can define the runspace where commands are run, open sessions on a local or remote computer, and invoke the commands either synchronously or asynchronously based on the needs of the application.

这意味着 PowerShell 主机实现了 PowerShell 会话。对于基本的标准主机,这可以是 powershell.exe,但出于多种原因,也可能有任意数量的替代应用程序或开发工具也可以实现自己的 PowerShell 主机。


无论您的 PowerShell 主机如何,AllHosts 配置文件位置都应保持标准,但不同的 PowerShell 主机通常会为其主机设置自己的 CurrentHost 配置文件位置。例如,powershell.exe 是它自己的 PowerShell 主机,并且将有它自己的特定于主机的配置文件,名为 Microsoft.PowerShell_profile.ps1PowerShell ISE 实现自己的 PowerShell 主机,并具有不同的主机特定配置文件,名为 Microsoft.PowerShellISE_profile.ps1.

如果您希望您的配置文件中的代码与主机无关,您应该确保将您的配置文件代码放在 AllHosts 配置文件之一中。特定于主机的代码,例如您只想在 ISE PowerShell 主机或 VSCode PowerShell 主机的上下文中可用的内容,应该进入特定于主机的配置文件。