通过批处理文件为系统设置环境变量

Sam*_*rsa 3 batch-file environment-variables windows-7

我正在使用一个.bat文件来自动执行我的引擎的某些任务(一旦从存储库中新鲜克隆它).其中一项任务是设置环境变量.我正在使用该SETX命令并设置命名变量的路径%CD%,即运行安装程序的目录.

这很好用,虽然用户需要log-off/log-on可能很烦人.log-off/log-on如果将变量设置为系统变量,则不需要此循环(我不确定为什么但重新启动Visual Studio对用户环境变量没有影响...也就是说,它检测到没有变化,但它会检测系统变量的变化) .所以我继续使用该-m命令.不幸的是,这要求批处理文件具有管理员权限.不是问题; 我以管理员身份运行批处理文件.好吧,现在我遇到了一个问题.当前目录变量,%CD%从运行安装程序的目录更改为C:\Windows\System32.

所以现在问题.如何通过批处理文件设置系统环境变量,该文件在%CD%没有默认值的情况下使用C:\Windows\System32.就像一个注释,很多人使用安装程序,我希望这个过程尽可能轻松无误.这意味着,不首选手动输入.目前,如果没有管理员权限而没有管理员权限-m,则唯一需要的是log-off/log-on循环.否则,一切都是自动化的.

ixe*_*013 5

%0是批处理文件的名称.您可以使用%~dp0 pushd来更改批处理文件所在的目录,然后从那里开始运行到任何目录.所以这种批处理文件的一般结构是:

@echo off
pushd %~dp0
rem batch file commands go here
popd
Run Code Online (Sandbox Code Playgroud)

至于Visual Studio问题...用户模式环境变量可用于设置环境变量后启动的每个进程.但由于某种原因,目前的流程没有收到它.但Explorer.exe(处理该开始菜单和运行命令的人似乎每次需要时都会获取环境的新副本.

以这种方式启动的进程将具有新环境,而从命令行启动的进程将继承旧环境,而不会设置新变量setx.

您可以通过将批处理文件更改为两者setsetx变量来缓解此问题.

这里有一些代码可以帮助您入门.它会

  1. 显示当前的工作目录
  2. 更改脚本所在的目录
  3. 在它正在运行的shell中设置变量MYTEST
  4. 在用户环境中设置变量
  5. 从shell启动记事本,这样您就可以尝试打开文件名%MYTEST%
    • 尝试使用%,它的工作原理
    • 请注意当前目录是如何更改的,顺便说一句.
  6. 要求您从开始菜单手动启动记事本

这是代码,HTH

@echo off

::This is where we start
echo Current directory is %CD%
echo %0

::We change the current directory to where the script is running
pushd %~dp0

echo Current directory is %CD%

::if you want, you can move relatively from it
cd..

::Set an environement variable
set MYTEST=%~f0
::Make a copy avaiable to other processes
setx MYTEST "%MYTEST%"

::Now I should be able to fire notepad and open %%MYTEST%% 
::(you can use the %% sign in the open box)
::Let's start a copy from this process
::
echo Starting notepad, open the file %%MYTEST%%, you should this 
echo file thanks to the set statement.
notepad
echo Now launch Notepad from the start menu and open the file %%MYTEST%%, 
echo you should this file thanks to the setx statement.

::Wherever you end up, restore the current directory
popd

echo Current directory is %CD%
Run Code Online (Sandbox Code Playgroud)