如何使用Windows批处理文件在其中找到目录并将其存储到变量中? [英] How do I find a directory in and store it into a variable, using a Windows batch file?
问题描述
我需要找到特定目录的位置,然后将该目录路径存储到Windows批处理脚本中的变量中.
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.
基本上,我需要在Linux/bash上实现类似的功能:
Basically I need the equivilent of somehting like this on Linux/bash:
export DIRPATH=`find / -name "DirectoryName" -print -quit`
感谢您的光临!
推荐答案
要批量获取命令的输出,您需要 FOR/F
.
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%
由于find命令中有引号,因此需要usebackq-option.而且必须一次转义管道字符,因为它应该管道 dir 命令,而不是 for 命令
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
这篇关于如何使用Windows批处理文件在其中找到目录并将其存储到变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!