带有* Token的Windows For循环

时间:2016-05-30 13:40:38

标签: windows batch-file

我正在尝试使用特定(绝对完整路径)和*通配符文件/文件夹名称的混合来显示文件/文件夹内容,但我的代码正在跳过*通配符搜索。我正在使用DIR命令进行搜索,因为它适用于文件夹/目录和文件。

SETLOCAL EnableDelayedExpansion
SET VAR="c:\users\admin\documents\" "my files*" "*.MYO" "backups" "history.*" "History" "*.db" "all accounts.txt"
SET "ArchiveInclude="
FOR %%a IN (%VAR%) DO (
 IF "!a::!"=="!a!" (
  SET LookUpSet=DIR /ON /B /S "%%~a"
  FOR /F "Delims=" %%F IN ('!LookUpSet!') DO (
   SET ArchiveInclude=!ArchiveInclude! "%%~F"
  )
 ) ELSE ( SET ArchiveInclude=!ArchiveInclude! "%%~a" )
)

不幸的是,ArchiveInclude不包含任何“我的文件*”“ .myo”或“history。”搜索结果。 %% a永远不会处理包含通配符的任何字符串*。

我需要ArchiveInclude来包含对指定的所有文件/文件夹的所有完整路径引用,例如

ECHO !ArchiveInclude!
"c:\users\admin\documents\" "c:\Users\User 3\my files here\" "c:\Users\User 1\Documents\my files01.txt" "c:\Users\User 1\Documents\my files02.txt" "c:\Users\User 1\Documents\my files01.jpg" "c:\Users\User 1\Documents\my files02.jpg" "c:\Users\User 2\Documents\My Account Files.MYO" "c:\Users\User 2\Documents\Business\Sales Accounts.MYO" "c:\Program Files\history.db" "c:\Program Files\history.txt" "c:\Users\User 1\Documents\History\" "c:\Users\User 1\Documents\Databases\afile.db" "c:\Users\User 1\Documents\Databases\data.db" "c:\Users\User 1\Documents\Databases\last.db" "c:\Users\User 2\Documents\all accounts.txt"

1 个答案:

答案 0 :(得分:0)

问题在于这一行:

FOR %%a IN (%VAR%) DO (

您已将VAR设置为以空格分隔的文件名列表,其中一些带有通配符。当您有通配符时,FOR命令在当前目录中搜索与通配符匹配的任何文件(类型FOR/?以获取帮助。)这不是您想要的。你不希望FOR在那一点上进行搜索;你只是希望它迭代给定的字符串而不管它们包含什么。

幸运的是,您甚至不必使用FOR,因为DIR命令可以使用多个参数。因此,您可以完全摆脱FOR行并改为执行此操作:

 SET LookUpSet=DIR /ON /B /S %VAR%