简体   繁体   English

使用批处理文件设置 windows 环境变量

[英]Set windows environment variables with a batch file

I was looking for a way to set the environment path variable with a .cmd file.我正在寻找一种使用 .cmd 文件设置环境路径变量的方法。
When the path variable was getting too long, I got some errors.当路径变量变得太长时,我得到了一些错误。
Just add the needed variables to 'Set Path variable' below只需将所需的变量添加到下面的“设置路径变量”中
Check the current value of your path variable and add to the script检查路径变量的当前值并添加到脚本
Run the script as administrator!以管理员身份运行脚本!
Open a new console window and it should work eg php -v打开一个新的控制台窗口,它应该可以工作,例如 php -v

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

I come at this question with a Linux perspective.我从 Linux 的角度来回答这个问题。 Usually setting an environment variable in Linux ( $myVar=1 ) only sets it for the current process but not any child process that it spawns.通常在 Linux 中设置一个环境变量( $myVar=1 )只为当前进程设置它,而不是它产生的任何子进程。

To allow any child process to read a variable you need to export envVar=2 .要允许任何子进程读取变量,您需要export envVar=2 In Windows the set command already does this for you.在 Windows 中, set命令已经为您执行此操作。 This is generally what you want.这通常是您想要的。

The setx command sets a variable permanently for the current user, but strangely enough this is not reflected in the current process, you will need to open another cmd.exe window for it to take effect. setx命令为当前用户永久设置了一个变量,但奇怪的是这并没有反映在当前进程中,您需要打开另一个cmd.exe窗口才能使其生效。

C:\> set foobar=1

C:\> powershell "echo ${env:foobar}"
1

C:\> setx barfoo 2

SUCCESS: Specified value was saved.

C:\> powershell "echo ${env:barfoo}"  # not present

C:\> 

Also notice the strictly necessary syntax difference between set and setx .还要注意setsetx之间严格必要的语法差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM