2

From Setting Windows PowerShell environment variables, I use this as admin:

PS D:\>[Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\bin", "Machine")

I restart the shell and check if it works:

PS D:\> $env:path.contains("C:\bin")
False

Why is that?

Ooker
  • 1,969
  • 4
  • 28
  • 58
  • Did you check it manually by simply outputting the whole environment variable `$env:path`? – Olaf May 15 '23 at 06:24
  • yes. It doesn't there. Plus that shouldn't the `$env:path.contains("C:\bin")` be suffice? – Ooker May 15 '23 at 06:26
  • You have to run this as administrator. You know that, don't you? Try `[Environment]::SetEnvironmentVariable("Path", $env:Path + "C:\bin", "Machine")` ... without the semikolon. At least that works on my machine. `¯\_(ツ)_/¯` – Olaf May 15 '23 at 06:40
  • Yes I ran it as admin. Without the semicolon it still doesn't work. I don't think removing it has any impact on here – Ooker May 15 '23 at 06:50
  • 1
    It might be some issue in your environment though. As I said - it works as intended on my machine. – Olaf May 15 '23 at 06:52
  • yes, but how do I identify that problem? – Ooker May 15 '23 at 06:52
  • 1
    I'd start with a reboot. ;-) – Olaf May 15 '23 at 06:55

1 Answers1

4

The System.SetEnvironmentVariable call manipulates the system registry key that holds the persisted environment. A call using GetEnvironmentVariable with the same parameters should show that it has been set in the persisted registry. However, your check is to launch a new process. New processes inherit their environment from the parent process which in the case of launching a command prompt from the desktop is Explorer. Explorer needs to be told the environment has changed. The system dialog that changes the environment broadcasts a WM_SETTINGCHANGE message to do this. Then Explorer re-reads the persisted registry key and new processes will start with the new environment variable values.

You may need to broadcast a WM_SETTINGCHANGE message to notify processes of the change. When I try your example in PowerShell however (as Administrator) it does work. So the broadcast window message should be being done for you already.

patthoyts
  • 32,320
  • 3
  • 62
  • 93
  • Example: this is how you [send WM_SETTINGCHANGE from a PowerShell script](https://gist.github.com/0xfeeddeadbeef/2c03971709f457bd726cea20c52f94d7) – Giorgi Chakhidze May 15 '23 at 09:08