Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here


Identify and Copy latest files in directory

Identify and Copy latest files in directory

Identify and Copy latest files in directory

Hi all,

Everyday around 7 AM there are 3 csv exports extracted into a specific folder and the file names are exactly the same each day except everyday the prefix of the file name is amended to the current date.


16-02-2018_Test1 will change to 17-02-2018_Test1

16-02-2018_Test2 will change to 17-02-2018_Test2

16-02-2018_Test3 will change to 17-02-2018_Test3

The file itself is not replaced, the new file with the current date is instead added to this folder.

What I need to do is identify the 3 extracts each day and copy them to a sub-folder. The best way I thought of doing this is by identifying the date at which the file was last modified.

I have the below VBS code I found and helps identifies the latest file in a directory and I added a line that will copy that file to a new directory.

The issue however, is that the code only identifies 1 file instead of 3 and I can only copy 1 file instead of 3. If anyone has better code to help me achieve the desired result or alternatively can help modify the existing code to achieve the desired result.

CODE --> vbs

sPath = "C:\Users\Desktop\Test\"

Const sToDir = "C:\Users\Desktop\Test\NewFolder\"

Set oFSO = CreateObject("Scripting.FileSystemObject")

sNewestFile = GetNewestFile(sPath)

If sNewestFile <> "" Then

   WScript.Echo "Newest file is " & sNewestFile

   dFileModDate = oFSO.GetFile(sNewestFile).DateLastModified
   If DateDiff("n", dFileModDate, Now) > 60 Then
	 oFSO.CopyFile sNewestFile, sToDir
   End If

   WScript.Echo "Directory is empty"
End If

Function GetNewestFile(ByVal sPath)

   sNewestFile = Null   ' init value

   Set oFSO = CreateObject("Scripting.FileSystemObject")
   Set oFolder = oFSO.GetFolder(sPath)
   Set oFiles = oFolder.Files

   ' enumerate the files in the folder, finding the newest file
   For Each oFile In oFiles
     On Error Resume Next
     If IsNull(sNewestFile) Then
       sNewestFile = oFile.Path
       dPrevDate = oFile.DateLastModified
     Elseif dPrevDate < oFile.DateLastModified Then
       sNewestFile = oFile.Path
	   dPrevDate = oFile.DateLastModified
     End If
     On Error Goto 0

   If IsNull(sNewestFile) Then sNewestFile = ""

   GetNewestFile = sNewestFile

End Function 

RE: Identify and Copy latest files in directory

Hi All, I found the answer on a different thread. Here is the link: https://stackoverflow.com/questions/48866113/ident...

Below is the code:

CODE --> vbs

Option Explicit

Dim FolderToCheck, FolderDestination, FileExt, mostRecent, noFiles, fso, fileList, file, filecounter, oShell, strHomeFolder

' Enumerate current user's home path - we will use that by default later if nothing specified in commandline
Set oShell = CreateObject("WScript.Shell")
strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%")

'Variables -----
folderToCheck = strHomeFolder & "\Desktop\MY\MMS"           ' Folder Source to check for recent files to copy FROM
folderDestination = strHomeFolder & "\Desktop\New"          ' Destination Folder where to copy files TO

fileExt = "txt"     ' Extension we are searching for
mostRecent = 2      ' Most Recent number of files to copy
' --------------

PreProcessing()     ' Retrieve Command Line Parameters

' Display what we are intending on doing
wscript.echo "Checking Source: " & FolderToCheck 
wscript.echo "For Files of type: " & FileExt
wscript.echo "Copying most recent "& mostRecent &" file(s) to: " & FolderDestination & "."

noFiles = TRUE

Set fso = CreateObject("Scripting.FileSystemObject")

Set fileList = CreateObject("ADOR.Recordset")
fileList.Fields.append "name", 200, 255
fileList.Fields.Append "date", 7

If fso.FolderExists(FolderToCheck) Then 
    For Each file In fso.GetFolder(FolderToCheck).files
     If LCase(fso.GetExtensionName(file)) = LCase(FileExt) then
       fileList("name").Value = File.Path
       fileList("date").Value = File.DateLastModified
       If noFiles Then noFiles = FALSE
     End If
    If Not(noFiles) Then 
        wscript.echo fileList.recordCount & " File(s) found. Sorting and copying last " & mostRecent &"..."
        fileList.Sort = "date DESC"
        If Not(fileList.EOF) Then 
            If fileList.recordCount < mostRecent Then 
                wscript.echo "WARNING: " & mostRecent &" file(s) specified but only " & fileList.recordcount & " file(s) match criteria. Adjusted to " & fileList.RecordCount & "."
                mostRecent = fileList.recordcount
            End If

            fileCounter = 0
            Do Until fileList.EOF Or fileCounter => mostRecent
                If Not(fso.FolderExists(folderDestination)) Then 
                    wscript.echo "Destination Folder did not exist. Creating..."
                    fso.createFolder folderDestination
                End If
                fso.copyfile fileList("name"), folderDestination & "\", True
                wscript.echo  fileList("date").value & vbTab & fileList("name")
                fileCounter = fileCounter + 1
            wscript.echo "An unexpected error has occured."
        End If
        wscript.echo "No matching """ & FileExt &""" files were found in """ & foldertocheck & """ to copy."
    End If
    wscript.echo "Error: Source folder does not exist """ & foldertocheck & """."
End If


Function PreProcessing
    Dim source, destination, ext, recent

    ' Initialize some variables
    Set source = Nothing
    Set destination = Nothing
    Set ext = Nothing
    Set recent = Nothing

    'Get Command Line arguments
    ' <scriptname>.vbs /Source:"C:\somepath\somefolder" /Destination:"C:\someotherpath\somefolder" /ext:txt /recent:2

    source = wscript.arguments.Named.Item("source")
    destination = wscript.arguments.Named.Item("destination")
    ext = wscript.arguments.Named.Item("ext")
    recent = wscript.arguments.Named.Item("recent")

    If source <> "" Then FolderToCheck = source
    If destination <> "" Then FolderDestination = destination
    If ext <> "" Then FileExt = ext
    If recent <> "" Then mostRecent = int(recent)

End Function 

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close