I can create a user environment variable within a Powershell script (Windows 10) easily.
[System.Environment]::SetEnvironmentVariable('name', 'value', 'User')
When the variable should contain another user environment variable like %OTHERVAR%;static_part, I found that the type must be ExpandString. This can be done as follows
Set-ItemProperty HKCU:\Environment 'name' 'value' -Type ExpandString
So, I wrote the following code
[System.Environment]::SetEnvironmentVariable('M2_HOME', 'C:\dev\app\apache-maven-3.3.9', 'User')
# special treatment to get expandable type
Set-ItemProperty HKCU:\Environment 'PATH' '%M2_HOME%\bin;C:\Users\UID20852\AppData\Local\Microsoft\WindowsApps;' -Type ExpandString
Write-Host ([System.Environment]::GetEnvironmentVariable('M2_HOME', 'User'))
Write-Host ([System.Environment]::GetEnvironmentVariable('PATH', 'User'))
Write-Host
Output:
C:\dev\app\apache-maven-3.3.9
C:\dev\app\apache-maven-3.3.9\bin;C:\Users\UID20852\AppData\Local\Microsoft\WindowsApps;
Everything is looking fine, both variables exist. When I open the Windows control to edit the user environment variables, I see both variables and the value of PATH is expanded. Even in regedit I see the type of the variables is correct.
However, when I open a new cmd and try to run a binary from %M2_HOME%\bin (should be on the PATH now), it fails.
To resolve the problem manually I just need to open the Windows control to edit the user environment variables, double-click the PATH variable, edit nothing, and close it again (I guess it re-writes it).
Then, in a new cmd, I can then run binaries from %M2_HOME%\bin.
Any ideas how I can make this PATH variable work just through the script?
[System.Environment]::SetEnvironmentVariable ...afterSet-ItemProperty HKCU:\Environment ...SetEnvironmentVariablenot only update registry by also send notification about it, thus any interested application (for exampleexplorer.exe) can know that them need to reread registry values. Also, AFAIK, there is no established order of user variables initialization, so dependency between per-user variables is not really supported.ExpandStringand it does not work as expected because the%...%placeholder is taken literally and not as placeholder