bat脚本设置系统环境变量即时生效

时间:2023-03-09 00:16:47
bat脚本设置系统环境变量即时生效

关于bat的资料多但零碎,记录一下。

1.设置环境变量即时生效:通过重启explorer来实现即时生效(亲测有效)

  @echo off

  set curPath=%cd%

  wmic ENVIRONMENT where "name='path' and username='<system>'" set VariableValue="%curPath%tool\dig;%path%" 

  taskkill /im explorer.exe /f
  @echo ================================================
  @echo 下面开始重启“explorer.exe”进程
  pause
  start explorer.exe

2.变量是否包含另一个变量判断

  set mypath=%path%

  set curPath=%cd%

  set digPath=%curPath%tool\dig
  echo %mypath% | find /i "%digPath%">nul && goto A || goto B
  :A /////系统dig环境变量已经存在
  echo 当前环境变量包含%digPath%
  exit

  :B /////不存在

  echo 当前环境变量不包含%digPath%
  exit

  注意:变量中是否包含字符串,使用同样的方法:echo %mypath% | find /i "ABC">nul && goto A || goto B

3.bat中打开exe程序:打开exe程序前需要先切换到exe所在的根目录

  ::切换到exe所在目录

  cd %curPath%tool
  
::启动程序
  start "" "%curPath%tool\operateToolWPF.exe"

关于bat批处理,推荐一个网站,资料很全:http://www.bathome.net