0

I have a script where i can copy any file to a different folder. May i know how i can edit this script to only copy the 2 latest date *text* file from C:. When it copies, it must overwrite the old file. Below is the script that i edited from a website. I am very beginner in scripting world.. Please help me...

  ' Copy a File 

  Const OverwriteExisting = TRUE 
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  objFSO.CopyFile "C:\Users\User\Desktop\MY\MMS\tag.txt" , "C:\Users\User\Desktop\new\", OverwriteExisting 
Damien
  • 1,490
  • 1
  • 8
  • 17
KSR
  • 31
  • 1
  • 1
  • 8

1 Answers1

1

You could use the following code - I'm not sure how it would behave with a large directory. I've made some assumptions based on your directory names, that it will be looking for a user's home folder, etc.

You can use command line parameters to call it and override the defaults, or you could just replace the strings in the Variables section:

cscript {scriptname}.vbs /source:"C:\somefoldername\folder" /destination:"C:\someotherfolder\folder" /ext:txt /recent:2

There's very basic error checking. It should overwrite files if they exist. It will also create the destination folder if it doesn't exist.

Try this (I've tested it, it does work on Windows 7 [and apparently Vista])

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 & "."
wscript.echo 

noFiles = TRUE

Set fso = CreateObject("Scripting.FileSystemObject")

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

If fso.FolderExists(FolderToCheck) Then 
    For Each file In fso.GetFolder(FolderToCheck).files
     If LCase(fso.GetExtensionName(file)) = LCase(FileExt) then
       fileList.AddNew
       fileList("name").Value = File.Path
       fileList("date").Value = File.DateLastModified
       fileList.Update
       If noFiles Then noFiles = FALSE
     End If
    Next
    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 
            fileList.MoveFirst
            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")
                fileList.moveNext
                fileCounter = fileCounter + 1
            Loop
        Else
            wscript.echo "An unexpected error has occured."
        End If
    Else
        wscript.echo "No matching """ & FileExt &""" files were found in """ & foldertocheck & """ to copy."
    End If
Else
    wscript.echo "Error: Source folder does not exist """ & foldertocheck & """."
End If

fileList.Close

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
Damien
  • 1,490
  • 1
  • 8
  • 17
  • Your script works fine in my PC. Actually i just want to schedule task this script to run once a month. The problem here is i need to click "ok" for every pop up message box. Is there any other solution where i can just run this script without clicking each time? – KSR Dec 27 '13 at 16:56
  • Cscript – Damien Dec 27 '13 at 17:26
  • Sorry i really do not know how to edit this with "Cscript – KSR Dec 27 '13 at 18:26
  • Either that or simply add an apostrophe ' to the start of each line in the script that has wscript.echo in it. – Damien Dec 27 '13 at 18:36
  • No problem. We got there in the end :) – Damien Dec 27 '13 at 18:52
  • :can I use this script on other PC? I tried just now but it is not working. When I execute, error message stated "C:\Documents and Settings\Mms\Desktop\Test.vbs. is this script only applicable for home PC only? – KSR Dec 28 '13 at 06:44
  • Looks like it is not picking up the environment variable for user home directory. What is the full path on that computer? What operating system is it? It looks to be an XP based computer judging by that path... – Damien Dec 28 '13 at 06:59
  • The source path:C:\Mms2 and destination:C:\Documents and Settings\Mms\Desktop\Test. This is Microsoft window 2000 PC for keeping database file in .MBB File. Script:C:\Documents and Settings\Mms\Desktop\Test.vbs line:90 char:5 error: obj doesn't support this property or method:'wscript.arguments.Named' code:800A01B6 source: Microsoft vbscript runtime error – KSR Dec 28 '13 at 07:38
  • On the 2000 machine comment out this line: PreProcessing() by adding an apostrophe ' at the begining of the line... eg; ' PreProcessing() – Damien Dec 28 '13 at 07:48
  • Also you might need to update folderToCheck = "C:\MMS2" and folderDestination = "C:\Documents and Settings\Mms\Desktop\Test" – Damien Dec 28 '13 at 07:49
  • Hi Damien, I tested it but could not copy the recent file. There is no any error message popped out. I just change the file ext to MBB and file to be copied =1.. – KSR Dec 28 '13 at 09:20
  • Hi - I am sorry but I do not have access to a win 2000 machine to test. Vbscript calls behave a little differently on other operating systems. Can you maybe start a new question explaining exactly what you want for your 2000 machine as all you existing variables seem to be different to your original question, different source, different number of files, etc. the existing code has only been tested on win7. – Damien Dec 28 '13 at 09:33
  • Ok Damien.. Anyway thanks a lot for your help. I will post a new question to solve this.. Actually I tested this at home before I try with other PC.. Sorry.. Your script works very well with vista – KSR Dec 28 '13 at 10:06
  • I will see if I can get hold of a win 2000 build and retest – Damien Dec 28 '13 at 10:10
  • Hi Damien, May i know how you post this script? I tried to post a new Question with your script but it says "Your post appears to contain code that is not properly formatted as code. Please indent all code by 4 spaces using the code toolbar button or the CTRL+K keyboard shortcut. For more editing help, click the [?] toolbar icon". – KSR Dec 28 '13 at 18:42
  • Indent your code with four spaces at the start of each line of code. – Damien Dec 28 '13 at 22:57