2

I need to find the location of a specific directory, and then store that directory path into a variable within a Windows batch script.

I also want the command to return when it finds a match (to avoid searching the entire hard drive once the directory has already been found).

So far I've tried this on the command line:

dir c:\ /s /b /ad | find "DirectoryName"

The problem with this is that it searches the entire drive, even after a match is found. Plus, I still can't figure out how to store the result in a variable within a batch file. There should only be a single result.

Basically I need the equivilent of somehting like this on Linux/bash:

export DIRPATH=`find / -name "DirectoryName" -print -quit`

Thanks for looking!

Mr. Shickadance
  • 5,283
  • 9
  • 45
  • 61
  • You need this change to the environment variable to be permanent, or only temporary for the duration of your batch file execution? – Laf Oct 11 '12 at 15:24
  • @Laf It only needs to be temporary for the batch file. Once I find this directory I need to copy in a few files. – Mr. Shickadance Oct 11 '12 at 15:53

1 Answers1

1

In batch you need FOR /F to get the output of a command.

FOR /F "usebackq delims=" %%p IN (`dir c:\ /s /b /ad ^| find "DirectoryName"`) DO (
  set "DIRPATH=%%p"
)
echo %DIRPATH%

As there are quotes in the find command you need the usebackq-option. And it's necessary to escape the pipe character one time, as it should pipe the dir command, not the for command

jeb
  • 78,592
  • 17
  • 171
  • 225
  • I'm having some trouble with this. I get `DirectoryName: no such file or directory`, which seems odd since find is searching plain text piped from dir, correct? – Mr. Shickadance Oct 11 '12 at 15:54
  • It works for me, there was only a missspelling in `usebachq` instead of `usebackq` – jeb Oct 11 '12 at 18:55