我有这种格式的文本文件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 session 。
如果您具有权限,则可以在计算机级别(2)启用环境变量,或者:
[Environment]::SetEnvironmentVariable("$Variable", "$file",2)
[Environment]::SetEnvironmentVariable("$Variable", "$file","Machine")
或者,仅是用户级别(1),或者:
[Environment]::SetEnvironmentVariable("$Variable", "$file",1)
[Environment]::SetEnvironmentVariable("$Variable", "$file","User")
HKEY_LOCAL_MACHINE
。 HKEY_CURRENT_USER
https://docs.microsoft.com/en-us/dotnet/api/system.environmentvariabletarget?view=netframework-4.7.2
关于powershell - 如何设置使用Powershell可以随时访问的环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55389633/