Tuesday, December 28, 2010

windows: setting environment variables from the command line

The standard route is rather slow and painful, even on Win7:
“MyComputer | Properties | Advanced System Settings | Environment Variables”… that’s a lot of clicks just to get to the point where you can add/edit an environment variable.

Thankfully, there’s a much easier alternative via the command line.

But first, did you know where the environment variables are stored on the file system? Until now I thought they were in some system config file, but it turns out they're actually stored in the registry itself (which technically is a system config file).
  • The logged-in user’s env variables go here:
    HKEY_CURRENT_USER\Environment
  • The machine-wide env variables go here:
    HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
The setx utility lets you change env variables for either the user or machine. The good old set command let’s you add/edit env variables too, but there are a few major differences from setx:
  • setx will permanently change the value of an env variable. The changes made by set last only for the current session.
  • Changes made by setx are not immediately visible – that is, they are not available to the current session. However, set’s changes are immediately visible.
  • You can’t delete env variables with setx, like you can with set. For example:
    set someVar=
    will delete the environment variable ‘someVar’ for the current session, but you can’t do something like this with setx.

    Instead, you have to use the “reg” utility to delete environment variables (that may or may not have been created with setx):
    REG delete HKCU\Environment /V someVar
Okay, so do you create a permanent environment variable via setx? It’s pretty straightforward:
  • To set an env variable for the current user:
    SETX <Variable> <Value>
  • To set an env variable for the machine (i.e. globally):
    SETX <Variable> <Value> -m
Example:
setx  CLASSPATH  C:\Users\ambars\.m2\repository\com\oracle\ojdbc14\10.2.0.1.0\ojdbc14-10.2.0.1.0.jar;C:\Program Files\Java\jre6\lib\ext\QTJava.zip;.

source: http://ss64.com/nt/setx.html

No comments: