FBryant87
FBryant87

Reputation: 4595

Powershell - Set environment variable without having to close applications

I assume this isn't possible, but when developing software getting up-to-date environment variables is a major pain.

As an example, I have a psake script which updates an env var my application requires:

[System.Environment]::SetEnvironmentVariable($myConfig, $myValue, 'Process')
[System.Environment]::SetEnvironmentVariable($myConfig, $myValue, [System.EnvironmentVariableTarget]::Machine)

This env var is something which may change on a daily/weekly basis as it's based on spun up Azure infrastructure.

In Visual Studio, my app relies on this env var for configuration, and it will not run successfully until I exit VS and reopen it again (so that the 'Machine' set env var is now up to date).

Is there anything which can be done to prevent us having to close and reopen everything again everytime an env var changes on Windows?

Upvotes: 1

Views: 361

Answers (1)

jfrmilner
jfrmilner

Reputation: 1768

The current Environment Variables can be read from the registry,

Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -Name myConfig

As a workaround, you could read the value from the registry and set the Environment Variable again to update your session without the need to reopen.

$myConfig = "myConfig"
$reg = Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -Name myConfig
$myValue = $reg.myConfig
[System.Environment]::SetEnvironmentVariable($myConfig, $myValue, 'Process')
[System.Environment]::SetEnvironmentVariable($myConfig, $myValue, [System.EnvironmentVariableTarget]::Machine)

Upvotes: 1

Related Questions