在 Powershell 5 中更改 PSModulePath
Changing the PSModulePath in Powershell 5
我使用以下方法永久更改了 PSModulePath:
[Environment]::SetEnvironmentVariable('PSModulePath', "ABC", "Machine")
当我调用下面的代码(returns“ABC”)时,它工作正常:
[Environment]::GetEnvironmentVariable('PSModulePath', "Machine")
但是在任何 Powershell 会话中当我 运行:
$env:PSModulePath
我得到:
C:\Users\myname\Documents\WindowsPowerShell\Modules;ABC
这条路是从哪里来的,是不是PS5魔术?我检查了“用户”目标,这是空白的。好像有什么东西在 PSModulePath 前面加上这个默认路径?
环境驱动器 Env:
包含特定于当前用户会话 (source) 的环境变量。它相当于 Process
作用域。所以
[Environment]::GetEnvironmentVariable('PSModulePath', 'Process')
应该等同于
$env:PSModulePath
Process
范围包含特定进程的环境变量。它的构造如下 (source):
This list of variables is inherited from the parent process and is constructed from the variables in the Machine and User scopes.
由于您同时检查了 Machine
和 User
范围,但没有找到路径,它必须来自父进程,即 PowerShell 本身。确实如此,可以阅读 here:
The CurrentUser module path is prefixed only if User scope $env:PSModulePath
doesn't exist. Otherwise, the User scope $env:PSModulePath
is used as defined.
正如您在问题中确认的那样,
[Environment]::GetEnvironmentVariable('PSModulePath', 'User')
为空,因此 $env:PSModulePath
以 CurrentUser 模块路径为前缀,根据您的 [=$HOME\Documents\PowerShell\Modules
或 $HOME\Documents\WindowsPowerShell\Modules
=28=].
您可以在我的回答中阅读有关环境变量的更多信息 。
我使用以下方法永久更改了 PSModulePath:
[Environment]::SetEnvironmentVariable('PSModulePath', "ABC", "Machine")
当我调用下面的代码(returns“ABC”)时,它工作正常:
[Environment]::GetEnvironmentVariable('PSModulePath', "Machine")
但是在任何 Powershell 会话中当我 运行:
$env:PSModulePath
我得到:
C:\Users\myname\Documents\WindowsPowerShell\Modules;ABC
这条路是从哪里来的,是不是PS5魔术?我检查了“用户”目标,这是空白的。好像有什么东西在 PSModulePath 前面加上这个默认路径?
环境驱动器 Env:
包含特定于当前用户会话 (source) 的环境变量。它相当于 Process
作用域。所以
[Environment]::GetEnvironmentVariable('PSModulePath', 'Process')
应该等同于
$env:PSModulePath
Process
范围包含特定进程的环境变量。它的构造如下 (source):
This list of variables is inherited from the parent process and is constructed from the variables in the Machine and User scopes.
由于您同时检查了 Machine
和 User
范围,但没有找到路径,它必须来自父进程,即 PowerShell 本身。确实如此,可以阅读 here:
The CurrentUser module path is prefixed only if User scope
$env:PSModulePath
doesn't exist. Otherwise, the User scope$env:PSModulePath
is used as defined.
正如您在问题中确认的那样,
[Environment]::GetEnvironmentVariable('PSModulePath', 'User')
为空,因此 $env:PSModulePath
以 CurrentUser 模块路径为前缀,根据您的 [=$HOME\Documents\PowerShell\Modules
或 $HOME\Documents\WindowsPowerShell\Modules
=28=].
您可以在我的回答中阅读有关环境变量的更多信息