VBScript自动查找和移动文件

时间:2012-01-05 21:38:44

标签: vbscript batch-file

我的任务是尝试在工作中自动执行任务,因为我们最近遇到了人们记住这样做的问题。

一般来说,这就是我需要脚本做的事情:

  1. 以YYYYMMDD
  2. 格式获取前一天的日期
  3. 输入具有该名称的文件夹
  4. 在该位置下的所有文件夹中搜索4个特定文件
  5. 将这些文件复制到多个不同的位置
  6. 我遇到的问题是,对于我要查找的4个文件,它们位于2个不同的文件夹中。 3合1,1合1。这些文件夹的名称每天都会更改,具体取决于它们在由其他软件生成时放入的队列。我需要移动这些文件,以便可以在它们上运行另一个脚本。我无法弄清楚如何实现这一目标。有人有想法吗?

1 个答案:

答案 0 :(得分:1)

如果包含感兴趣文件的文件夹是日期目录的子文件夹,则可以使用嵌套循环:

  Dim sDFolder : sDFolder    = "..\data\20110105"
  Dim dicFiNa  : Set dicFiNa = CreateObject("Scripting.Dictionary")
  dicFiNa("1.txt") = ""
  dicFiNa("3.txt") = ""
  dicFiNa("5.txt") = ""
  Dim oRDir     : Set oRDir  = goFS.GetFolder(sDFolder)
  Dim oSDir
  For Each oSDir In oRDir.SubFolders
      Dim oFile
      For Each oFile In oSDir.Files
          WScript.Echo "looking at", oFile.Path
          If dicFiNa.Exists(oFile.Name) Then
             WScript.Echo "found", oFile.Name, "will copy"
          End If
      Next
  Next

输出:

looking at E:\trials\SoTrials\answers\8750206\data\20110105\whatever\6.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\whatever\5.txt
found 5.txt will copy
looking at E:\trials\SoTrials\answers\8750206\data\20110105\unknown\4.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\unknown\3.txt
found 3.txt will copy
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\2.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\1.txt
found 1.txt will copy

如果你需要,完整的递归步行会更复杂一些。


只是为了好玩:一个递归版本:

  Dim sDFolder : sDFolder    = "..\data\20110105"
  Dim dicFiNa  : Set dicFiNa = CreateObject("Scripting.Dictionary")
  dicFiNa("1.txt")  = ""
  dicFiNa("3.txt")  = ""
  dicFiNa("55.txt") = ""
  Dim oRDir     : Set oRDir  = goFS.GetFolder(sDFolder)
  walk oRDir, dicFiNa, "whatever you need to copy the files"

Sub walk(oDir, dicFiNa, vCargo)
  Dim oItem
  For Each oItem In oDir.Files
      WScript.Echo "looking at", oItem.Path
      If dicFiNa.Exists(oItem.Name) Then
         WScript.Echo "found", oItem.Name, "will copy"
      End If
  Next
  For Each oItem In oDir.SubFolders
      walk oItem, dicFiNa, vCargo
  Next
End Sub

输出:

looking at E:\trials\SoTrials\answers\8750206\data\20110105\whatever\6.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\whatever\5.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\unknown\4.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\unknown\3.txt
found 3.txt will copy *
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\2.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\1.txt
found 1.txt will copy *
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\deep\deeper\55.txt
found 55.txt will copy *

(*)一旦解决了权限问题。