How to make PowerShell recognize changes in environment variables?

When I change any environment variable in Windows using GUI (System Properties/Environment Variables/System Variables) changes are reflected immediately in cmd terminal, but PowerShell shows an old value.

Here cmd recognized that I changed JAVA_HOME value from C:\Users\nikif\.jdks\openjdk-19.0.1 to C:\Users\nikif\.jdks\corretto-16.0.2

enter image description here

PowerShell still shows the previous value – C:\Users\nikif\.jdks\openjdk-19.0.1
enter image description here

Is there any command that will make PowerShell recognize the environment variable change made in GUI?
Or maybe there is a better way to change the environment variable from PowerShell?

Thank you.

>Solution :

This all should really be a comment (I tried above), but attempting to explain why the question, as it stands, is too vage requires just more explaination.

Processes get their environment when started by the OS. They basically get a copy the environment as it was at that point in time. When you start a process you can (using the respective APIs) pass additional or altered environment variables.

During the existance (runtime) of a process you cannot change the environment.
Shells are a common exception, as they provide specific syntax that does that (set NAME=VALUE in CMD.EXE and $env:NAME="VALUE" in PowerShell, for example). An application itself could also do such stuff from its code using respective APIs. But in general, there is no way to change variables from the outside.

One process will never see the changes done to the environment in a different process. For example, if you have to separate CMD.EXE sessions running and change a variable in one of them, the other will not know. The environment is private to each process.

A potential exception is the (global/system) environment variables you can set using the Computer/Properties/Environment setting (applet). The system will send a WM_SETTINGCHANGE window message indicating the that environment has changed. Applications can register to this message and act accordingly.

However, neither PowerShell nor CMD.EXE do seem to listen to this message (it would require a (hidden) Window anyway and both are console applications). And frankly, it would be not good if they did. Consider CMD.EXE just execuing a batch file and a variable (say PATH) changes underneath – security issues and general havoc all over.

Leave a Reply