如何使用.bat文件从PATH环境变量中删除特定的令牌? [英] How can I use a .bat file to remove specific tokens from the PATH environment variable?

查看:1933
本文介绍了如何使用.bat文件从PATH环境变量中删除特定的令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个卸载脚本,所以我想'撤消'修改安装到系统。为了实现这个目标,我想解析 PATH 变量,并删除安装添加到 PATH

I am writing an uninstallation script, so I would like to 'undo' modifications the installation made to the system. In achieving this goal, I would like to parse the PATH variable, and remove any values that the installation added to the PATH.

为此,我开发了以下伪代码 -

To do so, I developed the following pseudocode -


  • PATH 的内容保存到临时变量

  • 拆分 PATH 字符作为分隔符,并循环到每个标记

  • (In Loop )确定当前令牌是否是由安装添加的

  • 如果当前令牌未由安装添加,请保存它以添加到更新的 PATH (在临时变量中)

  • 保存更新的 PATH
  • Save the contents of PATH to a temporary variable
  • Split the PATH into tokens, using the ; character as a delimiter, and loop through each token
  • (In Loop) Identify if the current token is one added by the installation
  • (In Loop) If the current token was not added by the installation, save it to be added to the updated PATH (in a temporary variable)
  • Save the updated PATH

我希望这是相对直接的实现。

I expected this to be relatively straightforward to implement.

第一步,存储 PATH 很简单。

The first step, storing the PATH is simple.

SET TEMP_PATH=%PATH% 

但是,当我尝试循环访问每个令牌时,它将无法正常工作。

However, when I try to loop through each token, it will not work as I expected.

FOR /F "delims=;" %%A IN (%TEMP_PATH%) DO ECHO %%A 

此命令只输出第一个令牌,并且没有后续的令牌被回显。

This command only outputs the first token, and no subsequent tokens are echoed out.

因此,我有两个问题 -

So, I have two questions -


  • 如何循环遍历未知数量的令牌并处理每个令牌?

  • 是否有另一种方法实现相同的目标,可能更简单?

谢谢。

推荐答案

下面的批处理代码删除了在脚本顶部定义的一个或多个文件夹路径 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.

这篇关于如何使用.bat文件从PATH环境变量中删除特定的令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆