我明白了here ,可以在 Windows PowerShell 中点源脚本。如何获取用户的环境变量(或者保存用户变量的文件路径)?
示例.ps1:
[Environment]::SetEnvironmentVariable("PATH", "C:\newapp\bin", "User")
newapp --do-something # fails until PS restart
最佳答案
环境变量存储在注册表中,而不是文件中,并且它们会在 PowerShell 启动时自动加载。没有什么可以点源的。您可以通过列出 env:
PSDrive:
PS C:\> Get-ChildItem env: Name Value ---- ----- ALLUSERSPROFILE C:\ProgramData APPDATA C:\Users\jsmith\AppData\Roaming CommonProgramFiles C:\Program Files\Common Files ...
Environment variables differ from regular PowerShell variables in that they must be accessed via the env
scope prefix:
PS C:\> $username = 'foo' # ← PowerShell variable PS C:\> $username foo PS C:\> $env:username # ← environment variable jsmith
You can modify the current environment by making changes to the variables
PS C:\> $env:Path += ';C:\some\folder' # append C:\some\folder to PATH
or replacing them entirely:
PS C:\> $env:Path = 'C:\some\folder' # set PATH to C:\some\folder
It's not recommended to manipulate environment variables like $env:USERNAME
, though.
Note, however, that while you can modify environment variables or load them by dot-sourcing a file (using the proper prefix in the variable names) these variables are not persisted as they're applied to the process environment only.
To make persistent changes to environment variables you need to edit the values in the registry
Set-ItemProperty -Path 'HKCU:\Environment' -Name 'foo' -Value 'bar' -Type String
或使用.Net API
[Environment]::SetEnvironmentVariable('foo', 'bar', 'User')
请注意,pitfalls 可以通过 API 更改注册表值。
使用 setx
命令行实用程序也可以,但我不建议这样做,因为语法并不像人们希望的那么简单,而且 PowerShell 一开始就不需要外部程序。
您还可以通过从注册表中重新读取其值来更新进程启动后更改的环境变量:
$env:foo = [Environment]::GetEnvironmentVariable('foo', 'User')
但请注意,Windows 将用户和系统环境存储在不同的位置。如果您有一个像 $env:Path
这样在用户和系统环境中定义的变量,您需要组合这两个值:
$env:Path = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' +
[Environment]::GetEnvironmentVariable('Path', 'User')
如果您需要为当前进程更改并且持续存在的环境变量,您需要执行这两项操作:更改 $env:VARIABLE
并将更改后的变量写回注册表。如果您需要多次执行此操作,则建议将这两个操作包装在自定义函数中,例如像这样:
function Set-EnvVariable {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[String]$Name,
[Parameter(Mandatory=$true)]
$Value,
[Parameter(Mandatory=$false)]
[String]$Type = 'String'
)
if (Test-Path -LiteralPath "env:$Name") {
Set-Item "env:$Name" -Value $Value
} else {
New-Item -Path 'env:' -Name $Name -Value $value
}
Set-ItemProperty -Path 'HKCU:\Environment' -Name $Name -Value $Value -Type $Type
}
1 好吧,从技术上讲,包含(除其他外)用户环境变量的注册表部分存储在用户配置文件目录中的文件 ntuser.dat
中。然而,这在 PowerShell 中是无法进行点源的。
关于windows - 如何在 PowerShell 中获取用户环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51246716/