Monday, January 16, 2012

Powershell (v2) - Permanently Add Environmental Variable (for Real)

A while back I found a link that gave me an idea of how to do this:
Vista - how to set system's environment variable permanently
However, when I went to try this, it didn't actually take.  After doing some more digging, I found this post,
Add Path Environment Variable in PowerShell
which referenced an MSDN .NET link:
Environment.SetEnvironmentVariable Method (String, String, EnvironmentVariableTarget)
with three parameters instead of two.  After reading up on this, I tried this, and, it worked perfectly.
[Environment]::SetEnvironmentVariable("test","testvalue","Machine")
For more information on this third parameter (and what you can use with it) check out this link:
EnvironmentVariableTarget Enumeration 
As noted in this link, there are three targets you can point to with the method:
  1. Process: The environment variable is stored or retrieved from the environment block associated with the current process.

    The user creates the environment variable in a set operation.
    When the process terminates, the operating system destroys the environment variable in that process.
  2. User: The environment variable is stored or retrieved from the HKEY_CURRENT_USER\Environment key in the Windows operating system registry.

    When the user creates the environment variable in a set operation, the operating system stores the environment variable in the system registry, but not in the current process. If the user starts a new process, the operating system copies the environment variable from the registry to that process.

    When the process terminates, the operating system destroys the environment variable in that process. However, the environment variable in the registry persists until the user removes it programmatically or by means of an operating system tool.
  3. Machine: The environment variable is stored or retrieved from the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment key in the Windows operating system registry.

    When a user creates the environment variable in a set operation, the operating system stores the environment variable in the system registry, but not in the current process. If any user on the local machine starts a new process, the operating system copies the environment variable from the registry to that process.

    When the process terminates, the operating system destroys the environment variable in that process. However, the environment variable in the registry persists until a user removes it programmatically or by means of an operating system tool.

0 comments:

Post a Comment