Question : I need to create a script the copies the newest file from 1 directory to another

I  am new to Visual basics and need some help. I looked at the post linked below but could not undetstand it . Can anyone give me a sample script that a newbie can understand. I need a script that looks for the newest file in a folder and copies it from lets say dir1 into dir2.

http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_22925577.html

Answer : I need to create a script the copies the newest file from 1 directory to another

Hi, try this code.

Regards,

Rob.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Define the folder path to find the newest file here:
strSourceFolder = "C:\Temp\Folder1"
' Define the folder path to find the newest file here:
strTargetFolder = "C:\Temp\Folder2"

' Make sure the target folder has a trailing slash
If Right(strTargetFolder, 1) <> "\" Then strTargetFolder = strTargetFolder & "\"

' Here we call the GetNewestFile function, passing the path to the source folder for it to search
strNewestFilePath = GetNewestFile(strSourceFolder)

' Now copy the newest file to the target folder
objFSO.CopyFile strNewestFilePath, strTargetFolder, True

MsgBox strNewestFilePath & " was copied to " & strTargetFolder

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
   Next

   If IsNull(sNewestFile) Then sNewestFile = ""

   GetNewestFile = sNewestFile

End Function
Random Solutions  
 
programming4us programming4us