0

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?

1
  • Your Working folder is always located on your desktop ?
    – Hackoo
    Feb 2, 2017 at 12:45

2 Answers 2

2

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.

2
  • Thanks for the help, but I could not make it work. I just copied and pasted this code and modified the program name. Did you test that? Feb 2, 2017 at 14:20
  • 2
    I didn't need to test it because it's basic coding, it does work properly. The only way it may not work is if you're not running it from the same location as your previously working command line was running. As you were not responsible enough to provide a location I had to assume you would test in a like for like manner
    – Compo
    Feb 2, 2017 at 14:32
2

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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.