如何设置环境变量可以使用powershell随时访问?

How to set environment variable can access anytime using powershell?

我有这种格式的文本文件 12345。 我想将该值设置为环境变量,即使 powershell 关闭我也可以访问它。 当我想从命令行访问该环境变量时,我的期望是,我只使用这个命令:echo %ID% 并且它会显示 12345

$file = Get-Content .\file.txt
$Variable = "ID"
[Environment]::SetEnvironmentVariable("$Variable", "$file")

更新代码

我试过了,但我仍然无法从命令行使用此命令获取环境变量:echo %ID%

$file = Get-Content .\file.txt
$Variable = "ID"

[Environment]::SetEnvironmentVariable("$Variable", "$file",1)
[Environment]::SetEnvironmentVariable("$Variable", "$file","User")

[Environment]::SetEnvironmentVariable 的第三个参数允许您选择环境变量目标。默认为当前进程,因此使用两个参数调用只会使变量可用于当前 PowerShell 会话。

如果您有权限,您可以在机器级别 (2) 启用环境变量,或者:

[Environment]::SetEnvironmentVariable("$Variable", "$file",2)
[Environment]::SetEnvironmentVariable("$Variable", "$file","Machine")

或者,仅用户级别 (1),或者:

[Environment]::SetEnvironmentVariable("$Variable", "$file",1)
[Environment]::SetEnvironmentVariable("$Variable", "$file","User")
  • 'Machine Level' 在注册表中是 HKEY_LOCAL_MACHINE
  • 'User Level'是HKEY_CURRENT_USER

https://docs.microsoft.com/en-us/dotnet/api/system.environmentvariabletarget?view=netframework-4.7.2

您需要指定目标环境。默认情况下,该静态方法仅为当前进程设置 $Var/value 对。您可能希望当前用户使用它,因此请使用下面第一个 link 中列出的第二个方法,并将目标设置为 user。这是文档页面...

Environment.SetEnvironmentVariable 方法(系统) |微软文档
https://docs.microsoft.com/en-us/dotnet/api/system.environment.setenvironmentvariable?view=netframework-4.7.2

EnvironmentVariableTarget 枚举(系统)|微软文档
https://docs.microsoft.com/en-us/dotnet/api/system.environmentvariabletarget?view=netframework-4.7.2