Setting a system environment variable from a Windows batch file? Setting a system environment variable from a Windows batch file? windows windows

Setting a system environment variable from a Windows batch file?


The XP Support Tools (which can be installed from your XP CD) come with a program called setx.exe:

C:\Program Files\Support Tools>setx /?SETX: This program is used to set values in the environmentof the machine or currently logged on user using one of three modes.1) Command Line Mode: setx variable value [-m]   Optional Switches:    -m  Set value in the Machine environment. Default is User....For more information and example use: SETX -i

I think Windows 7 actually comes with setx as part of a standard install.


Simple example for how to set JAVA_HOME with setx.exe in command line:

setx JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"

This will set environment variable "JAVA_HOME" for current user. If you want to set a variable for all users, you have to use option "-m". Here is an example:

setx -m JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"

Note: you have to execute this command as Administrator.

Note: Make sure to run the command setx from an command-line Admin window


If you set a variable via SETX, you cannot use this variable or its changes immediately. You have to restart the processes that want to use it.

Use the following sequence to directly set it in the setting process too (works for me perfectly in scripts that do some init stuff after setting global variables):

SET XYZ=testSETX XYZ test