英文:
[Environment]::SetEnvironmentVariable doesn't set permanetly
问题
从设置 Windows PowerShell 环境变量中,我以管理员身份使用以下命令:
PS D:\> [Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\bin", "Machine")
然后重新启动 Shell 并检查是否生效:
PS D:\> $env:path.contains("C:\bin")
False
为什么会这样?
英文:
From Setting Windows PowerShell environment variables, I use this as admin:
PS D:\>[Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\bin", "Machine")
I restart the shell and check if it works:
PS D:\> $env:path.contains("C:\bin")
False
Why is that?
答案1
得分: 4
The System.SetEnvironmentVariable 调用操纵持久环境的系统注册表键。使用相同参数的 GetEnvironmentVariable 调用应该显示已在持久注册表中设置。然而,您的检查是启动新进程。新进程从父进程继承其环境,即从桌面启动命令提示符的情况下是 Explorer。必须告诉 Explorer 环境已更改。更改环境的系统对话框广播 WM_SETTINGCHANGE 消息以执行此操作。然后 Explorer 重新读取持久注册表键,新进程将使用新的环境变量值启动。
您可能需要广播 WM_SETTINGCHANGE 消息以通知进程进行更改。但是,当我尝试以 PowerShell 示例(以管理员身份)运行时,它确实有效。因此,广播窗口消息应该已经为您执行。
英文:
The System.SetEnvironmentVariable call manipulates the system registry key that holds the persisted environment. A call using GetEnvironmentVariable with the same parameters should show that it has been set in the persisted registry. However, your check is to launch a new process. New processes inherit their environment from the parent process which in the case of launching a command prompt from the desktop is Explorer. Explorer needs to be told the environment has changed. The system dialog that changes the environment broadcasts a WM_SETTINGCHANGE message to do this. Then Explorer re-reads the persisted registry key and new processes will start with the new environment variable values.
You may need to broadcast a WM_SETTINGCHANGE message to notify processes of the change. When I try your example in PowerShell however (as Administrator) it does work. So the broadcast window message should be being done for you already.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论