windows - 您将如何编写 .bat 或 .cmd 文件以从 PATH 中删除元素?

标签 windows scripting batch-file cmd

相关:
How to list the elements of the path in a batch file?
How does FOR work?

您将如何编写批处理文件或 CMD 文件来从路径中删除元素?它应该优雅地处理:

  • 大小写差异
  • 简称和长名

我已经使用 tr.exe 完成了此操作,但它速度慢且复杂,并且使用临时文件,这使得它变得更加复杂。

认为答案是这样的:

setlocal
set tpath="" 
set _path="%PATH:;=" "%"
for %%p in (%_path%) do (
   call :KeepIfNotEqual %%p %elementToRemove% 
)
endlocal & set path=%tpath%

...其中 %elementToRemove% 是要删除的路径元素。 KeepIfUnique 必须是一个带有两个参数的子例程 - 目录名称,对它们进行规范化,并将第一个参数附加到 tpath,如果它不等于第二个参数 (elementToRemove)。

正如我所说,我可以使用 tr.exe 执行此操作,但我可以仅使用 Windows cmd.exe shell 中的内置命令来执行此操作吗?

编辑:我想当您认真对待它时,问题是,如何在 cmd.exe 中进行大小写转换?

最佳答案

这是我根据 Igor 的提示想出的。

@echo off
goto START

-------------------------------------------------------
 rmpath.bat

 remove a path element from path 

 Created Tue Sep 15 21:33:54 2009 

-------------------------------------------------------

:START
SETLOCAL ENABLEDELAYEDEXPANSION 

@REM require one argument (the path element to remove)
if  _%1==_ goto USAGE

@REM  ~fs = remove quotes, full path, short names
set fqElement=%~fs1

@REM convert path to a list of quote-delimited strings, separated by spaces
set fpath="%PATH:;=" "%"

@REM iterate through those path elements
for %%p in (%fpath%) do (
    @REM  ~fs = remove quotes, full path, short names
    set p2=%%~fsp
    @REM is this element NOT the one we want to remove?
    if /i NOT "!p2!"=="%fqElement%" (
        if _!tpath!==_ (set tpath=%%~p) else (set tpath=!tpath!;%%~p)
    )
)

set path=!tpath!

@call :LISTPATH

goto ALL_DONE
-------------------------------------------------------

--------------------------------------------
:LISTPATH
  echo.
  set _path="%PATH:;=" "%"
  for %%p in (%_path%) do if not "%%~p"=="" echo     %%~p
  echo.
  goto :EOF
--------------------------------------------


--------------------------------------------
:USAGE
  echo usage:   rmpath ^<arg^>
  echo     removes a path element from the path.
  goto ALL_DONE

--------------------------------------------

:ALL_DONE
ENDLOCAL & set path=%tpath%

关于windows - 您将如何编写 .bat 或 .cmd 文件以从 PATH 中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1429988/

相关文章:

c++ - 在 Windows 7 中创建 POSIX 应用程序?

c++ - 使用自定义凭据提供程序的远程桌面连接

c++ - 如何使用 GetKeyState 获取按键被按下的那一刻

bash - 使用shell脚本登录监控并发送邮件

scripting - 一步以编程方式提取 tar.gz(在带有 7-Zip 的 Windows 上)

batch-file - "FINDSTR:"在调用函数中使用特殊字符时出错(批处理)

windows - Cygwin当前的完整安装大小是多少?

windows - 在 Windows 中自动执行任务的最佳方式

Windows 批量自动应答 XCOPY/i

java - 有什么好的方法可以通过 JDBC 原子地执行 MySQL 语句吗?