开发者

copy files between a specified date range

开发者 https://www.devze.com 2023-03-17 02:33 出处:网络
I want to copy files fro开发者_如何学Gom one folder to another which falls between a specific date range using VBS.

I want to copy files fro开发者_如何学Gom one folder to another which falls between a specific date range using VBS.

for example i want to copy files from 06/11/2009 to 06/12/2010. How can I do that in VB script.


Is WMI an option? If so, here's a sample script based on the one from the Hey, Scripting Guy! article How Can I Delete All Files Older Than a Specified Date?:

strComputer = "." 

strFolder = "C:\FromFolder"
strNewFolder = "C:\ToFolder"

strDateFrom = "20090611000000.000000+00" ' 06/11/2009
strDateTo   = "20100612000000.000000+00" ' 06/12/2010


Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")

Set colFiles = oWMI.ExecQuery _ 
    ("ASSOCIATORS OF {Win32_Directory.Name='" & strFolder & "'} WHERE " _ 
        & "ResultClass = CIM_DataFile")

For Each oFile in colFiles
    If oFile.CreationDate > strDateFrom And oFile.CreationDate < strDateTo Then
        'WScript.Echo "Full path:     " & oFile.Name
        'WScript.Echo "Creation date: " & oFile.CreationDate

        oFile.Copy strNewFolder & "\" & oFile.FileName & "." & oFile.Extension
        oFile.Delete
    End If
Next

Here's a slightly different variant where date checks are included in the WMI query:

strComputer = "."
strDateFrom = "20090611000000.000000+00" ' 06/11/2009
strDateTo   = "20100612000000.000000+00" ' 06/12/2010
strNewFolder = "C:\ToFolder"
iFlags = 48

Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")

Set colFiles = oWMI.ExecQuery( _
    "SELECT * FROM CIM_DataFile" & _
    " WHERE Drive = 'C:' AND Path = '\\FromFolder\\'" & _
    " AND CreationDate >= '" & strDateFrom & "'" & _
    " AND CreationDate <= '" & strDateTo & "'" _
    ,,iFlags)

For Each oFile in colFiles
    'WScript.Echo "Full path:     " & oFile.Name
    'WScript.Echo "Creation date: " & oFile.CreationDate

    oFile.Copy strNewFolder & "\" & oFile.FileName & "." & oFile.Extension
    oFile.Delete
Next

A few notes:

  • The script is non-recursive, that is, it only moves files from the source folder itself and not its subfolders.
  • Dates are specified in the UTC format. More info about this format is in the article I linked to.
  • WMI doesn't include methods for moving files and folders, so the script copies then deletes the files.


You can use the FileSystemObject. The following will get the date a file was created:

   Dim fso, myfile, d
   Set fso = CreateObject("Scripting.FileSystemObject")

   Set myfile = fso.GetFile("something.dat")
   d = myfile.DateCreated
   MsgBox d

Read more here.

Here is an example of how to loop through the files in a given folder. For each file, you can check the date, decide whether you like it, and if so copy the file.

0

精彩评论

暂无评论...
验证码 换一张
取 消