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

 

在 Windows 操作系统中,修改环境变量后需要重新打开命令行窗口或者重新启动计算机才能使修改生效。如果想要在不重启计算机或者重新打开命令行窗口的情况下立即生效,可以使用以下方法: 1. 在 bat 脚本中使用 `setx` 命令修改环境变量,并且在修改后使用 `set` 命令强制更新当前窗口的环境变量,示例代码如下: ``` setx PATH "%PATH%;C:\NewFolder" /M set PATH=%PATH% ``` 其中,`setx` 命令用于修改系统环境变量 PATH,`/M` 参数表示修改的是系统级别的环境变量。`set` 命令用于强制更新当前窗口的环境变量,将新的环境变量值同步到当前窗口的进程中。 2. 在 bat 脚本中使用 `setx` 命令修改环境变量后,使用 `SendMessage` API 发送消息给 Windows Explorer 进程,通知它更新环境变量。示例代码如下: ``` setx PATH "%PATH%;C:\NewFolder" /M setlocal EnableDelayedExpansion set "msg=!WM_SETTINGCHANGE!" set "explorer=%SystemRoot%\explorer.exe" set "param=/select,explorer.exe" set "param=!param:\=\\!" set "param=!param:,=\,! /e,!param:~0,-1!!" if defined PROCESSOR_ARCHITEW6432 ( set "pids=" for /f "usebackq tokens=2 delims==;" %%i in (`tasklist /fi "imagename eq explorer.exe" /fi "memusage gt 50000" /fo list /v`) do ( set "pids=!pids! %%i" ) if defined pids ( echo ^<%time%^> Killing processes !pids:~1! to force Explorer restart... taskkill /pid !pids:~1! /f >nul 2>&1 ) ) else ( for /f "usebackq tokens=2 delims==;" %%i in (`tasklist /fi "imagename eq explorer.exe" /fi "memusage gt 25000" /fo list /v`) do ( set "explorer=%%i" ) ) echo ^<%time%^> Spawning Explorer process %explorer% %param%... start "" "%explorer%" %param% endlocal ``` 其中,`setx` 命令用于修改系统环境变量 PATH,`/M` 参数表示修改的是系统级别的环境变量。`SendMessage` API 用于向 Windows Explorer 进程发送消息,通知它更新环境变量。在代码中,使用了一些技巧来找到 Windows Explorer 进程的 PID,并且使用 `taskkill` 命令杀掉这些进程,然后使用 `start` 命令启动一个新的 Windows Explorer 进程,并且带上指定的参数。这样就可以在不重启计算机或者重新打开命令行窗口的情况下立即生效修改环境变量
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值