views:

381

answers:

4
  • Windows 7.
  • It's for my own machine, so it doesn't matter if it requires admin rights or something.
  • Preferably in Python or .NET, but I can learn a bit of Win32 (C/C++) programming if it's necessary.
A: 

Use the Environment class like this:

Environment.SetEnvironmentVariable("foo", "bar");
will
I forgot to mention, is that just for the duration of the program or is it permanent?
Javier Badia
It will affect the current program environment only. System wide changes are in the registry (see ghostdog's answer) and require the program to be relaunched after making the change.
Joshua
+4  A: 

if you want to permanently set environment variable, you can insert the new value into registry. eg with vbscript, add the path "c:\test" into PATH variable

Set WshShell = WScript.CreateObject("WScript.Shell")
strReg = "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path"
strSetting = WshShell.RegRead(strReg)
strNewSetting = strSetting&";c\test"
WshShell.RegWrite strReg, strNewSetting

So, if you use Python or other languages, you can do the same thing using your language's own api/modules to read and write registry

ghostdog74
Just save this as .vbs and run it.
Sebastián Grignoli
+1  A: 

Programmatically modifying environment variables is only for the duration of the program. Have not heard of actually modifying the environment system-wide and making it effective there and then. I do not think that can be done, that would require poking around at privileged level and possibly messing with the core system to achieve that.

Even under Unix, it cannot be done despite some hacks to achieve it. I do remember seeing code that actually did modify the environment variables under MSDOS, by altering the MSDOS's _psp environment data structure, but that was a single-tasking system and 16bit with no protection whatsoever.

To sum up, I do not think you can and it would be unwise to do so, it could be perceived as if the system is under a threat by a 'trojan' or a 'virus' as a result if attempting to do so, not alone that, as a user, I would not like for a program to modify the system environment variable without my consent! Sure, a program can write to the registry to make it permanent, but I would still like to know what is the purpose of it and why.

Hope this helps, Best regards, Tom.

tommieb75
+1  A: 

In C# the following creates a permanent environment variable:

Environment.SetEnvironmentVariable("foo", "bar", EnvironmentVariableTarget.Machine);
kicsit
Will this become permanent?
Javier Badia
It depends on the value of the EnvironmentVariableTarget enumeration used. See http://msdn.microsoft.com/en-us/library/system.environmentvariabletarget.aspx
kicsit