Setting a system environment variable from a Windows batch file?

Is it possible to set a environment variable at the system level from a command prompt in Windows 7 (or even XP for that matter). I am running from an elevated command prompt.

When I use the set command ( set name=value ), the environment variable seems to be only valid for the session of the command prompt.


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

C:Program FilesSupport Tools>setx /?

SETX: This program is used to set values in the environment
of 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)Javajdk1.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)Javajdk1.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=test
SETX XYZ test
链接地址: http://www.djcxy.com/p/30336.html

上一篇: 如何在Python中设置环境变量

下一篇: 从Windows批处理文件设置系统环境变量?