Reputation: 131
In CMD I can search a file with the following command:
DIR /S /B PROGRAM.EXE
If the file is found the result will be:
C:\Users\Dev\Desktop\Program.exe
I would like to get in the output just the directory without the file name C:\Users\Dev\Desktop\
to assign only the path to a variable.
Is there any way to do this at CMD?
Upvotes: 0
Views: 160
Reputation: 38719
Use a For
loop like this:
For /F "Delims=" %A In ('Dir/B/S/A-D "Program.exe" 2^>Nul') Do @Echo=%~dpA
Double up the %
in a batch file.
In a batch file, to set any matches as a variable use this structure:
@Echo Off
Set "i=0"
For /F "Delims=" %%A In ('Dir/B/S/A-D "Program.exe" 2^>Nul') Do (Set/A "i+=1"
Call Set "OnlyPath[%%i%%]=%%~dpA")
Set OnlyPath[
Timeout -1
Each match will be set as a different variable just to ensure that if more than one match is made you retrieve them all.
Upvotes: 2
Reputation: 18857
With a batch file, you can do someting like that :
@echo off
set "Working_Folder=%userprofile%\Desktop"
For /F "Delims=" %%F In ('Dir /B /S /A-D "%Working_Folder%\PROGRAM.exe" 2^>Nul') Do (
Set "MyFolder=%%~dpF"
)
Echo "%MyFolder%" & pause>nul
Upvotes: 2