windows 使用批处理文件查找文件并返回完整路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13876771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 10:07:47  来源:igfitidea点击:

Find file and return full path using a batch file

windowsfilebatch-filedirectory

提问by ABANDOND ACOUNT

Is it possible to create a batch file that searches for a file name, then returns its path so I can use it in a variable?

是否可以创建一个批处理文件来搜索文件名,然后返回其路径以便我可以在变量中使用它?

回答by Bali C

for /r C:\folder %%a in (*) do if "%%~nxa"=="file.txt" set p=%%~dpnxa
if defined p (
echo %p%
) else (
echo File not found
)

If the file you searched for was found it will set the variable %p%to the full path of the file including name and extension.

如果找到了您搜索的文件,它会将变量设置%p%为文件的完整路径,包括名称和扩展名。

If you just want the path (as in the folder path without the file) then use set p=%%~dpainstead.

如果您只想要路径(如在没有文件的文件夹路径中),请set p=%%~dpa改用。

Note: If there is more than 1 file with the same name then the variable will be set to the last one found. Also the script after the forloop line isn't really necessary, just to show you if it found anything :)

注意:如果有 1 个以上的文件同名,则变量将设置为找到的最后一个。此外,for循环行之后的脚本也不是必需的,只是为了向您展示它是否找到了任何东西:)

If you want to do it using the dircommand then use this, same rules apply

如果您想使用该dir命令执行此操作,请使用此命令,同样的规则适用

for /f "tokens=*" %%a in ('dir acad.exe /b /s') do set p=%%a

回答by Deb

Do this: -

做这个: -

for /f "delims=" %%F in ('dir /b /s "C:\File.txt" 2^>nul') do set MyVariable=%%F

for /f "delims=" %%F in ('dir /b /s "C:\File.txt" 2^>nul') do set MyVariable=%%F

Assuming you are searching Cdrive for File.txt.

假设您正在搜索C驱动器File.txt