开发者

Programmatically modifiy environment variables?

    开发者_开发百科
  • 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.


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


In C# the following creates a permanent environment variable:

Environment.SetEnvironmentVariable("foo", "bar", EnvironmentVariableTarget.Machine);


or you could try a Windows PowerShell script; PowerShell is installed on Windows 7 by default.

run powershell.exe

PS C:\> [Environment]::SetEnvironmentVariable("TestVariable", "Test value.", "User")

Then, for example, from cmd.exe

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\>echo %TestVariable%
Test value.

C:\>

Or (in a new) powershell.exe

PS C:\> echo $ENV:TestVariable
Test Value.
PS C:\>

check out http://technet.microsoft.com/en-us/library/ff730964.aspx


For anyone else looking for a quick commandline answer

SETX is available on windows servers (natively i think - http://technet.microsoft.com/en-us/library/cc755104.aspx )

Its also available in the Windows 7 and 8 toolkit.


Use the Environment class like this:

Environment.SetEnvironmentVariable("foo", "bar");


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜