如何从注册表更新 Windows PowerShell 会话环境变量? [英] How to update Windows PowerShell session environment variables from registry?

查看:106
本文介绍了如何从注册表更新 Windows PowerShell 会话环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的问题,但我找不到正确的答案.

This could be a simple question, but I couldn't find a proper answer.

如何在不关闭当前会话的情况下更新当前 Windows PowerShell 会话中的环境变量?

How do you update the environment variables from within a current Windows PowerShell session without closing the current one?

到目前为止,当我从控制面板>系统修改PATH环境变量时,我必须关闭当前会话并打开一个新会话,以便变量被刷新,或者发出一个很麻烦的 SetEnviromentVariable.

Up to now, when I modify for example the PATH environment variable from Control Panel > System, I have to close current session and open a new one, so that variables are refreshed, or issue a SetEnviromentVariable which is cumbersome.

我来自 Linux 世界,所以我正在寻找类似 source 命令的东西.

I'm coming from the Linux world, so I'm looking for something like source command.

推荐答案

环境在进程启动时被填充,这就是您需要重新启动进程的原因.

The environment gets populated on process start-up which is why you'll need to restart the process.

您可以通过从注册表中读取来更新环境.也许使用如下脚本:

You can update the environment by reading it from the registry. Maybe with a script like the following:

function Update-Environment {
    $locations = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
                 'HKCU:\Environment'

    $locations | ForEach-Object {
        $k = Get-Item $_
        $k.GetValueNames() | ForEach-Object {
            $name  = $_
            $value = $k.GetValue($_)

            if ($userLocation -and $name -ieq 'PATH') {
                Env:\Path += ";$value"
            } else {
                Set-Item -Path Env:\$name -Value $value
            }
        }

        $userLocation = $true
    }
}

(未经测试)

这篇关于如何从注册表更新 Windows PowerShell 会话环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆