How do I find a directory in and store it into a variable, using a Windows batch file?

只愿长相守 提交于 2021-01-28 07:15:51

问题


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!


回答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



来源:https://stackoverflow.com/questions/12842173/how-do-i-find-a-directory-in-and-store-it-into-a-variable-using-a-windows-batch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!