How could you write a .bat or .cmd file to remove an element from PATH?

Related:
How to list path elements in a batch file?
How does FOR work?

How would you write a batch file or CMD file to remove an element from a path? It should handle gracefully:

  • differences in case
  • short names and long names

I did this with tr.exe, but it is slow and complex and uses temporary files, which makes it even more complex.

I think the answer looks something like this:

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

... where% elementToRemove% is the path element to delete. KeepIfUnique should be a routine that takes two arguments - directory names, normalizes them and adds the first argument to tpath if it is not equal to the second argument (elementToRemove).

, tr.exe, windows cmd.exe?

: , , , case- cmd.exe?

+5
3

, .

@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%
+4

if

if /I "Blah"=="blah" (echo true) else (echo false)

if /? . , :

if /?
call /?
for /?
set /?
+1

- Cheeso... , .

script , , :

@echo off
  . . .
  . . .
SETLOCAL ENABLEDELAYEDEXPANSION
  . . .
  . . .
endlocal & set path=%tpath%

: "tpath" , cmd.exe , "endlocal".

"PATH", .

0

All Articles