Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

How to update Windows PowerShell session environment variables from registry?

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

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

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.

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

question from:https://stackoverflow.com/questions/14381650/how-to-update-windows-powershell-session-environment-variables-from-registry

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:SYSTEMCurrentControlSetControlSession ManagerEnvironment',
                 '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
    }
}

(untested)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...