I want to extract a full path from the PATH
environment variable with native cmd tools. Consider the following PATH
content:
C:\Program Files\Windows Resource Kits\Tools\;C:\Perl\site\bin;C:\Perl\bin;C:\WI
NDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;c:\Program Files\Microsoft SQ
L Server\90\Tools\binn\;C:\WINDOWS\system32\WindowsPowerShell\v1.0;C:\Program Fi
les\Microsoft SQL Server\80\Tools\Binn\;C:\Program Files\Microsoft SQL Server\10
0\DTS\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;c:\program fil
es\nmap\;C:\Program Files\WinRAR\;C:\Program Files\QuickTime\QTSystem\;C:\Progra
m Files\hydra-5.4-win\;C:\Program Files\john1701\run;C:\dig;;C:\cygwin;C:\wamp\b
in\mysql\mysql5.0.45\bin;C:\Program Files\MySQL\MySQL Server 5.0\bin;C:\Program
Files\Tail4win;C:\Program Files\Overlook Fing 1.1\bin
I want to extract only the following path:
C:\Program Files\MySQL\MySQL Server 5.0\bin;
Is FOR
capable of such thing?
You can use for
to tokenize at ;
but you need to take care of paths that have a ;
in them (and thus need quotes). All in all I'd say you'd build a pretty brittle solution with pretty much code at this point.
If you want to know where a certain executable is, then
for %%i in ("mysql.exe") do @echo.%%~$PATH:i
will tell you that (or not, if it's nowhere in the PATH
).
UPDATE: Ok, I got it. One nasty little batch file follows:
@echo off
setlocal enabledelayedexpansion enableextensions
set p=%PATH%
:loop
for %%i in ("notepad.exe") do call :setvar "%%~$p:i"
if not :%x%:==:: (call :clearpath & goto loop)
goto :eof
:setvar
set x=%~1
goto :eof
:clearpath
echo %x%
for %%x in ("!x!") do set d=%%~dpx
set d=!d:~,-1!
set p=!p:%d%=!
goto :eof
This will print all matching paths from PATH
where notepad.exe
was found (the first program I know off the top of my head to be in two places here). Adapt accordingly for your problem.
:clearpath
simply deletes the found path from the variable and then we try matching again, until no match is left.
That said, this is still very un-pretty.
If you already know the path, why do you need to find it in the PATH string?
Or to put it another way, do you know a way of recognising that string, given that it may vary between installations?
alternatively, you can use vbscript.
Set objFS=CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
strSearch = objArgs(0)
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshPath = WshShell.Environment("SYSTEM")
strPath =WshPath("Path")
s = Split(strPath,";")
For i=LBound(s) To UBound(s)
If InStr(1,s(i),strSearch,1) > 0 Then
WScript.Echo s(i)
End If
Next
save the above as findpath.vbs and use it like this on the command line to find any string you want within the PATH variable:
c:\test> cscript //nologo findpath.vbs mysql
In a batch file, to get the results, use a for loop