批处理脚本返回文件的path

我想写一个代码,将显示我定义的文件的path。 例如,我有两个文件

  1. d:\testing\ ExecuteScript.bat
  2. d:\文档.txt

我希望在脚本中定义文件名“document.txt”,并返回“D:\ Test \ ExecuteScript.bat”。 我也尝试了下面的代码:

for(* document.txt)中的/ r %% x回显“%% x”

但是 ,只有当document.txt位于文件夹内而ExecuteScript.bat位于文件夹之外时,这才起作用,例如:

  1. d:\ ExecuteScript.bat
  2. d:\testing\ document.txt的

我已经search了许多在线解决scheme,但其中许多要求我把C:\放在我不想要的代码的前面。 非常感谢提前,并为我可怜的英语感到遗憾。

要告诉for /R哪里开始搜索文件,只需说明/R后面的路径:

 for /R "D:\" %%x in ("*document.txt") do echo "%%~x" 

如果您正在搜索同一个驱动器,则以下就足够了:

 for /R "\" %%x in ("*document.txt") do echo "%%~x" 

这里是你输入for /?时帮助出现的摘录for /?

 FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters] Walks the directory tree rooted at [drive:]path, executing the FOR statement in each directory of the tree. If no directory specification is specified after /R then the current directory is assumed. If set is just a single period (.) character then it will just enumerate the directory tree. 

如果你想搜索所有的驱动器,你可以做到以下几点:

 rem // Loop through all drive letters: for %%d in (ABCDEFGHIJKLMNOPQRSTU VWXYZ) do ( rem // Temporarily try to change to root of current drive: pushd "%%d:\" 2> nul && ( rem // Drive found, so search it for matching files: for /R %%x in ("*document.txt") do echo "%%~x" popd ) )