且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用.bat文件从PATH环境变量中删除特定的令牌?

更新时间:2023-11-14 07:51:03

下面的批处理代码删除了在脚本顶部定义的一个或多个文件夹路径 PathToRemove1 PathToRemove2 ,...从

The batch code below removes 1 or more folder paths as defined at top of the script with PathToRemove1, PathToRemove2, ... from




  • HKEY_LOCAL_MACHINE \System\CurrentControlSet\Control\Session Manager \Environment 下存储在Windows注册表中的 code>

  • user PATH of current user account stored in Windows registry under key
    HKEY_CURRENT_USER\Environment
  • system PATH stored in Windows registry under key
    HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment

系统 PATH 的更新需要管理员权限,

The update of system PATH requires administrator privileges which means the batch file must be executed as administrator if user account control (UAC) is not disabled for the user account executing the batch file.

批处理代码仅适用于Windows Vista和更高版本的Windows操作系统因为

The batch code works only for Windows Vista and later versions of Windows because of


  • reg.exe 的输出与Windows XP不同,对于非常旧的Windows 2000,这将需要不同的方法来获得用户和系统的当前值 PATH ,如两次 skip = 4 ,而不是 skip = 2 适用于Windows XP与 reg.exe 3.0版



  • 命令 SETX 默认情况下不适用于Windows XP或以前版本的Windows。

  • output of reg.exe is different for Windows XP and also different for very old Windows 2000 which would require a different method to get current value of user and system PATH like twice skip=4 instead of skip=2 for Windows XP with reg.exe version 3.0

    and
  • command SETX is by default not available on Windows XP or even former versions of Windows.

对于 reg.exe 输出差异,请参阅Rob van der Woude的使用REG查询读取NT的注册表

For the reg.exe output differences see Rob van der Woude's Reading NT's Registry with REG Query.

有关 SETX 命令的可用性, http://ss64.com/nt/setx.html =nofollow> SetX 和Microsoft的 SetX 文档。

For availability of command SETX see SS64 article about SetX and Microsoft's SetX documentation.

有关为什么不使用本地 PATH 正在执行批处理文件时定义的读取

For an explanation why not using local PATH as currently defined on execution of the batch file read the questions, answers and comments of

  • Why are other folder paths also added to system PATH with SetX and not only the specified folder path?
  • Setting path environment variable in batch file only once on Win7

已从用户和系统中删除文件夹路径的批注代码 PATH

Commented batch code for folder path removal from user and system PATH:

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "PathToRemove1=C:\Temp\Test"
set "PathToRemove2=C:\Temp"

rem Get directly from Windows registry the system PATH variable value.
for /F "skip=2 tokens=3" %%P in ('%SystemRoot%\System32\reg.exe query "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" /v "Path" 2^>nul') do (
    set "SystemPath=%%P"
    goto CheckSystemPath
)
echo Error: System environment variable PATH not found in Windows registry.
echo.
goto UserPath

:CheckSystemPath
rem Does the system PATH not end with a semicolon, append one temporarily.
if not "%SystemPath:~-1%" == ";" set "SystemPath=!SystemPath!;"

rem Check case-insensitive for the folder paths to remove as defined at top
rem of this batch script and remove them if indeed found in system PATH.
set "PathModified=0"
for /F "tokens=1* delims==" %%I in ('set PathToRemove') do (
    if not "!SystemPath:%%J;=!" == "!SystemPath!" (
        set "SystemPath=!SystemPath:%%J;=!"
        set "PathModified=1"
    )
)

rem Remove the semicolon at end of system PATH if there is one.
if "%SystemPath:~-1%" == ";" set "SystemPath=!SystemPath:~0,-1!"

rem Update system PATH using command SETX which requires administrator
rem privileges if the system PATH needs to be modified at all.
if "%PathModified%" == "1" (
    %SystemRoot%\System32\setx.exe PATH "%SystemPath%" /M
)

:UserPath
rem Get directly from Windows registry the user PATH variable value.
for /F "skip=2 tokens=3" %%P in ('%SystemRoot%\System32\reg.exe query "HKCU\Environment" /v "Path" 2^>nul') do (
    set "UserPath=%%P"
    goto CheckUserPath
)
rem This PATH variable does often not exist and therefore nothing to do here.
goto PathUpdateDone

:CheckUserPath
rem Does the user PATH not end with a semicolon, append one temporarily.
if not "%UserPath:~-1%" == ";" set "UserPath=!UserPath!;"

rem Check case-insensitive for the folder paths to remove as defined at top
rem of this batch script and remove them if indeed found in user PATH.
set "PathModified=0"
for /F "tokens=1* delims==" %%I in ('set PathToRemove') do (
    if not "!UserPath:%%J;=!" == "!UserPath!" (
        set "UserPath=!UserPath:%%J;=!"
        set "PathModified=1"
        if "!UserPath!" == "" goto DeleteUserPath
    )
)

rem Remove the semicolon at end of user PATH if there is one.
if "%UserPath:~-1%" == ";" set "UserPath=!UserPath:~0,-1!"
if "%UserPath%" == "" goto DeleteUserPath

rem Update user PATH using command SETX which does not require administrator
rem privileges if the user PATH needs to be modified at all.
if "%PathModified%" == "1" (
    %SystemRoot%\System32\setx.exe PATH "%UserPath%"
)
goto PathUpdateDone

:DeleteUserPath
rem Delete the user PATH as it contains only folder paths to remove.
%SystemRoot%\System32\reg.exe delete "HKCU\Environment" /v "Path" /f >nul

:PathUpdateDone
rem Other code could be inserted here.
endlocal

上面的批处理代码使用简单的不区分大小写的字符串替换和case-敏感字符串比较,以检查要删除的当前路径是否存在于用户或系统 PATH 中。这只有在众所周知文件夹路径是如何添加之前,并且用户尚未修改它们在此期间工作。要检查 PATH 是否包含文件夹路径的更安全方法,请参阅如何检查目录是否存在的答案%PATH%? dbenham 撰写。

The batch code above uses a simple case-insensitive string substitution and a case-sensitive string comparison to check if the current path to remove is present in user or system PATH. This works only if it is well known how the folder paths were added before and the user has not modified them in the meantime. For a safer method of checking if PATH contains a folder path see the answer on How to check if directory exists in %PATH%? written by dbenham.

为了理解所使用的命令及其工作方式,请打开命令提示符窗口,执行以下命令,并仔细阅读每个命令显示的所有帮助页面。

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.


  • echo /?

  • endlocal /?

  • 代表/? code>

  • if /?

  • reg /?

  • reg delete /?

  • reg query /?

  • rem /?

  • set /?

  • setlocal /?
  • setx /?

  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • reg /?
  • reg delete /?
  • reg query /?
  • rem /?
  • set /?
  • setlocal /?
  • setx /?

关于使用命令重定向运算符了解 < code>< code>与转义的< nul 2> nul c $ c> ^ 使用重定向来执行 reg.exe ,而不是解释 2> nul 放置在命令 FOR 中,这将导致由于语法错误导致由Windows命令解释程序退出批处理。

See also Microsoft's article about Using command redirection operators for an explanation of >nul and 2>nul with redirection operator > being escaped with ^ to use the redirection on execution of reg.exe instead of interpreting 2>nul misplaced for command FOR which would result in an exit of batch processing by Windows command interpreter because of a syntax error.