Is there any command line tool that can be used to edit environment variables in Windows?

Is there any command line tool that can be used to edit environment variables in Windows?

It would be nice if this was smart tool, for example:

  • When adding some path to let's say the PATH variable and this path is already there it shouldn't double this entry.
  • Inserting a new path to the PATH variable should be possible before/after some other path or in specific order (the first, the 7th, the last etc.).
  • It should be possible to change only part of variable's value (in case of the PATH a given path from a list of all paths).

And the last but not the least - I want my changes to persist between sessions so simple SET is out of question...

There's very nice GUI tool for this called Path Editor and I need something like this but for command line.


Solution 1:

I don't know any tool that does this, but maybe you can use the regcommand:

reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path

to read the current path, and

reg add "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /d "newPath" /f

to write your new value.

You need admin rights for hsving right acccess in HKLM. If that is a problem, consider modifying the user specific path setting in HKCU\Environment instead.

Solution 2:

If you need a generic way to set any environment variable and have the changes persist, then setx.exe would be the tool to use. It cannot do the "smart" things you are asking for, though...

setx.exe is included with Windows Vista or later; if you use an earlier version of Windows, you can use the above download link to get it.