none
A script for copying certain files to a new location

    Question

  • I have a folder with over 50,000 images in it. I need about 15,000 of them copied to another folder.

    Is there a script (that I can paste the list of the ones I need copied) to perform this action?

    Thanks in advance.
    Thursday, April 02, 2009 3:13 PM

Answers

  • You can use this script to copy files from one folder to another.
    The files you want to copy should be specified in the text file that you specify using the strFileList constant.
    Use the constants to specify source folder, target folder and if files should be overwritten or not if they already exist at the target.
    The script doesn't output anything if a file is copied successfully. If you want that for logging reasons add Wscript.echo strFileToCopy copied successfully or whatever you want it to say after the line ' File copied successfully
    Then run the script using cscript cscriptname.vbs and if you want the result logged to a file you can just type cscript cscriptname.vbs > logfile.log instead


    Option Explicit
    
    ' The source path for the copy operation.
    Const strSourceFolder = "H:"
    
    ' The target path for the copy operation.
    Const strTargetFolder = "C:\Temp\Target\"



    ' The list of files to copy. Should be a text file with one file on each row. No paths - just file name.
    Const strFileList = "C:\filelist.txt" ' Should files be overwriten if they already exist? TRUE or FALSE. Const blnOverwrite = FALSE



    Dim
    objFSO Set objFSO = CreateObject("Scripting.FileSystemObject") Const ForReading = 1 Dim objFileList Set objFileList = objFSO.OpenTextFile(strFileList, ForReading, False) Dim strFileToCopy, strSourceFilePath, strTargetFilePath On Error Resume Next Do Until objFileList.AtEndOfStream ' Read next line from file list and build filepaths strFileToCopy = objFileList.Readline strSourceFilePath = objFSO.BuildPath(strSourceFolder, strFileToCopy) strTargetFilePath = objFSO.BuildPath(strTargetFolder, strFileToCopy)
    ' Copy file to specified target folder. Err.Clear objFSO.CopyFile strSourceFilePath, strTargetFilePath, blnOverwrite If Err.Number = 0 Then
    ' File copied successfully
    Else
    ' Error copying file Wscript.Echo "Error " & Err.Number & " (" & Err.Description & "). Copying " & strFileToCopy End If Loop

    Let me know if you have any questions.

    Per
    Thursday, April 02, 2009 5:06 PM

All replies

  • You can use this script to copy files from one folder to another.
    The files you want to copy should be specified in the text file that you specify using the strFileList constant.
    Use the constants to specify source folder, target folder and if files should be overwritten or not if they already exist at the target.
    The script doesn't output anything if a file is copied successfully. If you want that for logging reasons add Wscript.echo strFileToCopy copied successfully or whatever you want it to say after the line ' File copied successfully
    Then run the script using cscript cscriptname.vbs and if you want the result logged to a file you can just type cscript cscriptname.vbs > logfile.log instead


    Option Explicit
    
    ' The source path for the copy operation.
    Const strSourceFolder = "H:"
    
    ' The target path for the copy operation.
    Const strTargetFolder = "C:\Temp\Target\"



    ' The list of files to copy. Should be a text file with one file on each row. No paths - just file name.
    Const strFileList = "C:\filelist.txt" ' Should files be overwriten if they already exist? TRUE or FALSE. Const blnOverwrite = FALSE



    Dim
    objFSO Set objFSO = CreateObject("Scripting.FileSystemObject") Const ForReading = 1 Dim objFileList Set objFileList = objFSO.OpenTextFile(strFileList, ForReading, False) Dim strFileToCopy, strSourceFilePath, strTargetFilePath On Error Resume Next Do Until objFileList.AtEndOfStream ' Read next line from file list and build filepaths strFileToCopy = objFileList.Readline strSourceFilePath = objFSO.BuildPath(strSourceFolder, strFileToCopy) strTargetFilePath = objFSO.BuildPath(strTargetFolder, strFileToCopy)
    ' Copy file to specified target folder. Err.Clear objFSO.CopyFile strSourceFilePath, strTargetFilePath, blnOverwrite If Err.Number = 0 Then
    ' File copied successfully
    Else
    ' Error copying file Wscript.Echo "Error " & Err.Number & " (" & Err.Description & "). Copying " & strFileToCopy End If Loop

    Let me know if you have any questions.

    Per
    Thursday, April 02, 2009 5:06 PM
  • Too Cool! Too fast! I don't know how to thank you enough. Took less than 30 minute to copy thos 15,000 file to a ne folder. This would have taken me days, maybe weeks, to manually complete that task. You should submit this to be included with the scripting archive. I am quite sure ther is someone elso who could use it.

    HPjr
    Friday, April 03, 2009 1:19 AM
  • Yes this is exactly what I am looking for!!!  BUT I am an absolute idiot when it comes to scripts.  If you could give me more detail on where to put this script to be  able to run it, that would be great.  I need the dummies instructions to do exactly what this thread is intended from start to finish.  If you need to contact me directly u can at evanraisbeck@apersonaloccasion.net THANK YOU in advance
    Saturday, April 25, 2009 8:50 AM
  • Open notepad

    Paste the contents of the script and edit the source path, target path and path to your file list.

    Save as, select all file types and save the script with a name that ends with .vbs for example c:\myscript.vbs


    vbs scripts are possible to run by double clicking them but this script is better run from a command prompt using the command cscript.exe c:\myscript.vbs
    The script runs silently. It doesn't produce any output at all if everything is fine but will let you know if something is wrong. You'll have to check the target folder files to see the progress.

    Saturday, April 25, 2009 9:20 AM
  • Hello, Your script work fine for me. The only thing that I would need, is a dialog bog that open when you start the script. A dialog box that ask me where is the txt file, what is the sorce folder and what is the destination folder. Once it's done, clic process and then it does it's thing.

    Is it complicated to do?

    tks

    Seby
    Saturday, April 25, 2009 2:27 PM
  • Awesome I got it to work. That's cool.  And I agree with Seby20  but I can do without it. Thank You so much.
    Sunday, April 26, 2009 6:46 AM
  • Browsing for folders is possible but the problem is that there's no native way of browsing for files in vbscript. There were a number of ways to do it in XP but as far as I know, none of them work in Vista unless you rely on third party components.
    If an inputbox where you enter the file path/name would do it for you it's easier but that's not much better than changing the path in the script.
    Sunday, April 26, 2009 12:14 PM
  • Ok, well, Could you do it like this....
    If my txt file is alway at the same place, it's not a problem, I just overwrite it every time.
    But as for files to be copied, it change all the times.
    So Can it open a dialog box to tell that look in this folder, all the files are there.
    And then start the program copy alone after i've selected the folder?
    The destination folder could ask to where I wanna copy those file.

    tks

    Seby
    Sunday, April 26, 2009 12:59 PM
  • How about this then?

    I added browse dialogs for the folder selections and I rebuilt the output method so that only a summary is shown at the end if it is run using wscript (double click).
    If it is run under cscript it will echo a summary at the end as well as results for each file as they are being copied.
    I hope it will suit your needs.
    Option Explicit
    
    ' The list of files to copy. Should be a text file with one file on each row. No paths - just file name.
    Const strFileList = "c:\filelist.txt"
    
    ' Should files be overwriten if they already exist? TRUE or FALSE.
    Const blnOverwrite = TRUE
    
    Dim objFSO
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    
    Dim objShell
    Set objShell = CreateObject("Shell.Application")
    
    Dim objFolder, objFolderItem
    
    ' Get the source path for the copy operation.
    Dim strSourceFolder
    Set objFolder = objShell.BrowseForFolder(0, "Select source folder", 0 )
    If objFolder Is Nothing Then Wscript.Quit
    Set objFolderItem = objFolder.Self
    strSourceFolder = objFolderItem.Path
    
    ' Get the target path for the copy operation.
    Dim strTargetFolder
    Set objFolder = objShell.BrowseForFolder(0, "Select target folder", 0 )
    If objFolder Is Nothing Then Wscript.Quit
    Set objFolderItem = objFolder.Self
    strTargetFolder = objFolderItem.Path
    
    
    Const ForReading = 1
    Dim objFileList
    Set objFileList = objFSO.OpenTextFile(strFileList, ForReading, False)
    
    Dim strFileToCopy, strSourceFilePath, strTargetFilePath
    Dim strResults, iSuccess, iFailure
    iSuccess = 0
    iFailure = 0
    
    On Error Resume Next
    Do Until objFileList.AtEndOfStream
        ' Read next line from file list and build filepaths
        strFileToCopy = objFileList.Readline
        strSourceFilePath = objFSO.BuildPath(strSourceFolder, strFileToCopy)
        strTargetFilePath = objFSO.BuildPath(strTargetFolder, strFileToCopy)
        ' Copy file to specified target folder.
        Err.Clear
        objFSO.CopyFile strSourceFilePath, strTargetFilePath, blnOverwrite
        If Err.Number = 0 Then
            ' File copied successfully
            iSuccess = iSuccess + 1
            If Instr(1, Wscript.Fullname, "cscript.exe", 1) > 0 Then
                ' Running cscript, output text to screen
                Wscript.Echo strFileToCopy & " copied successfully"
            End If
        Else
            ' Error copying file
            iFailure = iFailure + 1
            TextOut "Error " & Err.Number & " (" & Err.Description & ") trying to copy " & strFileToCopy
        End If
    Loop
    
    strResults = strResults & vbCrLf
    strResults = strResults & iSuccess & " files copied successfully." & vbCrLf
    strResults = strResults & iFailure & " files generated errors" & vbCrLf
    Wscript.Echo strResults
    
    Sub TextOut(strText)
        If Instr(1, Wscript.Fullname, "cscript.exe", 1) > 0 Then
            ' Running cscript, use direct output
            Wscript.Echo strText
        Else
            strResults = strResults & strText & vbCrLf
        End If
    End Sub
    Sunday, April 26, 2009 1:57 PM
  • It worked!!!!!!
    Thanks very much my friend!!!
    Last question..
    Is is possible that when it open for browsing to open a default place on my harddrive lets say D:\seby\photos\2009\
    And then I just have to select inside of 2009 instead of browsing through all the folders everytime.
    Same thing for the output.

    tks again. you're the best man!!!

    seby


    Sunday, April 26, 2009 3:45 PM
  • Yes, that's easy to fix. You just have to add an option to the BroweForFolder commands.
    Like this:
    Set objFolder = objShell.BrowseForFolder(0, "Select target folder", 0 , "D:\seby\photos\2009")

    Sunday, April 26, 2009 4:03 PM
  • Again thank you very much sir.

    Seby

    Monday, April 27, 2009 12:57 AM
  • A very big help thanks!
    Tuesday, April 28, 2009 7:26 PM
  • Hi, Thanks for your script. It has really helped newbies to scripting like us. My challenge is that I want to modify the script to only copy files with names "similar" and not "exactly the same" as the filenames in the text file.For example if the script sees a file name like 'WXXXKI23334', it should search the source location and copy the files having filenames with at least this characters e.g. '00WXXXK123334L' should be copied since it has contains 'WXXXK123334'. Please help.
    Wednesday, May 13, 2009 4:52 PM
  • It's not that difficult to modify the script to use the entries in the input file as search patterns.

    You will need to modify these two lines:
    strSourceFilePath = objFSO.BuildPath(strSourceFolder, strFileToCopy)
    strTargetFilePath = objFSO.BuildPath(strTargetFolder, strFileToCopy)

    Change them to this:
    strSourceFilePath = objFSO.BuildPath(strSourceFolder, "*" & strFileToCopy & "*")
    strTargetFilePath = strTargetFolder

    However, that would make the output of the script totally inaccurate.
    There's no good way to count the files that are being copied using the CopyFile method when you're using wildcards so the easiest thing would be to remove the logging functions or just ignore the file counts completely.

    If it's important to report on the number of files being copied the script must be totally rewritten and I don't feel like that right now so I hope that you can manage with this small change.

    • Proposed as answer by sansouchi Thursday, May 14, 2009 5:32 PM
    Wednesday, May 13, 2009 9:31 PM
  • Thanks for your response. I do not really need very accurate output, anything similar to what is in the fillist would do. Also it is not important to know the number of files copied. I would modify the script and let you know how it goes. Thank you very much for even responding. I am very grateful.
    Thursday, May 14, 2009 8:14 AM
  • Thanks. It worked fine for me. Hope it does for others too
    Thursday, May 14, 2009 5:32 PM
  • This works great, thank you!  How do i copy all files in a directory to a new direcotry and then automate the process?
    Friday, May 15, 2009 6:08 PM
  • That's really another issue and much simpler, just this line in a batch script (.bat .cmd): copy c:\folder\*.* d:\folder\
    Or if it has to be in vbscript: http://www.microsoft.com/technet/scriptcenter/scripts/storage/files/stfivb02.mspx

    When it comes to automating I guess you mean scheduling.
    Use task scheduler to configure your script to run at certain times or events.
    Saturday, May 16, 2009 11:58 AM
  • perhof,
    After much googling, I was fortunate enough to find your beautiful script!

    I added a couple of things like subfolder recusion ( by tweaking scripts I found) .
    Would you be kind enough to look this over and see if it's ok or needs fixing?
    Thanks for any help,
    ec

    [code]

    ' Read a list of images from text file
    ' and copy those images from SourceFolder\SubFolders to TargetFolder

    ' Should files be overwriten if they already exist? TRUE or FALSE.
    Const blnOverwrite = TRUE

    Dim objFSO, objShell, WSHshell, objFolder, objFolderItem, strExt, strSubFolder
    Dim objFileList, strFileToCopy, strSourceFilePath, strTargetFilePath
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objShell = CreateObject("Shell.Application")
    Set WSHshell = CreateObject("WScript.Shell")
    Const ForReading = 1

    ' Make the script useable on anyone's desktop without typing in the path
    DeskTop = WSHShell.SpecialFolders("Desktop")
    strFileList = DeskTop & "\" & "images.txt"

    ' File Extension type
    strExt = InputBox("Please enter the File type" _
    & vbcrlf & "For Example: jpg or tif")
    If strExt="" Then
       WScript.Echo "Invalid Input, Script Canceled"
    Wscript.Quit
    End if

    ' Get the source path for the copy operation.
    Dim strSourceFolder
    Set objFolder = objShell.BrowseForFolder(0, "Select source folder", 0 )
    If objFolder Is Nothing Then Wscript.Quit
    Set objFolderItem = objFolder.Self
    strSourceFolder = objFolderItem.Path

    ' Get the target path for the copy operation.
    Dim strTargetFolder
    Set objFolder = objShell.BrowseForFolder(0, "Select target folder", 0 )
    If objFolder Is Nothing Then Wscript.Quit
    Set objFolderItem = objFolder.Self
    strTargetFolder = objFolderItem.Path

    Set objFileList = objFSO.OpenTextFile(strFileList, ForReading, False)

    On Error Resume Next
    Do Until objFileList.AtEndOfStream
        ' Read next line from file list and build filepaths
        strFileToCopy = objFileList.Readline & "." & strExt

        ' Check for files in SubFolders
        For Each strSubFolder in EnumFolder(strSourceFolder)
          For Each strFileToCopy in oFSO.GetFolder(strSubFolder).Files

        strSourceFilePath = objFSO.BuildPath(strSubFolder, strFileToCopy)
        strTargetFilePath = objFSO.BuildPath(strTargetFolder, strFileToCopy)
        ' Copy file to specified target folder.
        Err.Clear
        objFSO.CopyFile strSourceFilePath, strTargetFilePath, blnOverwrite
        If Err.Number = 0 Then
            ' File copied successfully
            iSuccess = iSuccess + 1
            If Instr(1, Wscript.Fullname, "cscript.exe", 1) > 0 Then
                ' Running cscript, output text to screen
                Wscript.Echo strFileToCopy & " copied successfully"
            End If
        Else
            ' Error copying file
            iFailure = iFailure + 1
            TextOut "Error " & Err.Number & _
            " (" & Err.Description & ")trying to copy " & strFileToCopy
        End If
       Next
    Next
    Loop

    strResults = strResults + 0 '& vbCrLf
    strResults = strResults & iSuccess & " files copied successfully." & vbCrLf
    strResults = strResults & iFailure & " files generated errors" & vbCrLf
    Wscript.Echo strResults

    Sub TextOut(strText)
        If Instr(1, Wscript.Fullname, "cscript.exe", 1) > 0 Then
            ' Running cscript, use direct output
            Wscript.Echo strText
        Else
            strResults = strResults & strText & vbCrLf
        End If
    End Sub

    Function EnumFolder(ByRef vFolder)
    Dim oFSO, oFolder, sFldr, oFldr
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    If Not IsArray(vFolder) Then
    If Not oFSO.FolderExists(vFolder) Then Exit Function
    sFldr = vFolder
    ReDim vFolder(0)
    vFolder(0) = oFSO.GetFolder(sFldr).Path
    Else sFldr = vFolder(UBound(vFolder))
    End If
    Set oFolder = oFSO.GetFolder(sFldr)
    For Each oFldr in oFolder.Subfolders
    ReDim Preserve vFolder(UBound(vFolder) + 1)
    vFolder(UBound(vFolder)) = oFldr.Path
    EnumFolder vFolder
    Next
    EnumFolder = vFolder
    End Function
    [/code]

    Thursday, September 17, 2009 3:02 PM
  • anyone has the script to copy db from one location(local system) to another location ( in the ftp server ).the files should be replaced 
    Thursday, July 12, 2012 9:41 AM
  • Hi,

    This question is already marked as answered. If you still need help, please start a new question.

    Bill

    Thursday, July 12, 2012 2:16 PM
    Moderator
  • Hi Bill,

    The blog is very much educative.. thanks for sharing your expertise..

    I have a question regarding scripts, which are used to move files from one folder to another, wherein I have many files placed in a folder at the same time, however I need to move files one by one to another folder and there should be a time delay of atleast 1 min between each file movement... is this possible??

    Any information regarding this will be of a great help..

    Thanks and Regards,

    Manjunath

    Wednesday, December 12, 2012 2:25 PM
  • Hi there.

    Thanks for your script. What should I add in the code to copy the file and rename (add the number at the end) if the file has been already copied to the destination folder. For example everyday at the start up of windows I want to copy .pst file (everyday backup) to the destination folder but do not want to overwrite the previous copy (need to keep 30 each day copies).

    Take care


    • Edited by XJamesJX Friday, October 11, 2013 3:35 PM spelling
    Friday, October 11, 2013 3:13 PM
  • Boom! Perfect. I used it to copy pictures from my Google Drive to my local PC, but only missing files. I had prepared a list using this link: http://answers.microsoft.com/en-us/windows/forum/windows_7-files/how-to-compare-two-folders-in-win-7-prof-64bit/f99f7b3d-43a9-49d8-b8eb-6b550103e726

    I manually copied lines from one text file to a new one where the lines were different to use in this script.

    Then the script above...

    Thank you!


    student

    Wednesday, January 01, 2014 3:05 AM
  • Subj: Script to copy individual files from different source directories to one target.
    I wish to use the (above) script to copy individual files which reside in different source directories to one target directory. (In my case the target is on a different drive on my workstation.)
    Example:
    1st Source: C:\Data\Checks\MyChecks.xlsx
    2nd Source: C:\Mail\Primary.pst
    3rd Source: C:\Quicken\Current.QBW
    Target: E:\CriticalFiles
    (If it matters -- E:\ is on a different hard disk, recognized in file manager.)

    Restating Question:
    Obviously the above script works with one (1) source directory and no paths in filelist.txt.
    Question is how to include several individual files in several different directories in the source to one (1) target directory.

    Thank you.
    David W. Johnson


    David W. Johnson


    Saturday, January 11, 2014 8:14 PM
  • Since this topic is answered, closed and very old please post in a new question of your own. I would start by reviewing the forum posting guidelines at: http://social.technet.microsoft.com/Forums/en-US/a0def745-4831-4de0-a040-63b63e7be7ae/posting-guidelines?forum=ITCG


    ¯\_(ツ)_/¯

    Saturday, January 11, 2014 8:28 PM
  • Thank you very much for putting this script out here. Instead of copying the file what is the command that I can use to move the files from one folder to another could you please let me know what I need to change in below script. 

    Option Explicit

    ' The list of files to copy. Should be a text file with one file on each row. No paths - just file name.
    Const strFileList = "M:\Move.csv"

    ' Should files be <g class="gr_ gr_278 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="278" id="278">overwriten</g> if they already exist? TRUE or FALSE.
    Const blnOverwrite = TRUE

    Dim objFSO
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Dim objShell
    Set objShell = CreateObject("Shell.Application")

    Dim objFolder, objFolderItem

    ' Get the source path for the copy operation.
    Dim strSourceFolder
    Set objFolder = objShell.BrowseForFolder(0, "Select source folder", 0 )
    If objFolder Is Nothing Then Wscript.Quit
    Set objFolderItem = objFolder.Self
    strSourceFolder = objFolderItem.Path

    ' Get the target path for the copy operation.
    Dim strTargetFolder
    Set objFolder = objShell.BrowseForFolder(0, "Select target folder", 0 )
    If objFolder Is Nothing Then Wscript.Quit
    Set objFolderItem = objFolder.Self
    strTargetFolder = objFolderItem.Path


    Const ForReading = 1
    Dim objFileList
    Set objFileList = objFSO.OpenTextFile(strFileList, ForReading, False)

    Dim strFileToCopy, strSourceFilePath, strTargetFilePath
    Dim strResults, iSuccess, iFailure
    iSuccess = 0
    iFailure = 0

    On Error Resume Next
    Do Until objFileList.AtEndOfStream
        ' Read next line from file list and build filepaths
        strFileToCopy = objFileList.Readline
        strSourceFilePath = objFSO.BuildPath(strSourceFolder, strFileToCopy)
        strTargetFilePath = objFSO.BuildPath(strTargetFolder, strFileToCopy)
        ' Copy file to specified target folder.
        Err.Clear
        objFSO.CopyFile strSourceFilePath, strTargetFilePath, blnOverwrite
        If Err.Number = 0 Then
            ' File copied successfully
            iSuccess = iSuccess + 1
            If Instr(1, Wscript.Fullname, "cscript.exe", 1) > 0 Then
                ' Running <g class="gr_ gr_277 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="277" id="277">cscript</g>, output text to screen
                Wscript.Echo strFileToCopy & " copied successfully"
            End If
        Else
            ' Error copying file
            iFailure = iFailure + 1
            TextOut "Error " & Err.Number & " (" & Err.Description & ") trying to copy " & strFileToCopy
        End If
    Loop

    strResults = strResults & vbCrLf
    strResults = strResults & iSuccess & " files copied successfully." & vbCrLf
    strResults = strResults & iFailure & " files generated errors" & vbCrLf
    Wscript.Echo strResults

    Sub TextOut(strText)
        If Instr(1, Wscript.Fullname, "cscript.exe", 1) > 0 Then
            ' Running <g class="gr_ gr_276 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="276" id="276">cscript</g>, use direct output
            Wscript.Echo strText
        Else
            strResults = strResults & strText & vbCrLf
        End If
    End Sub


    • Edited by Ali.Sameer Thursday, November 02, 2017 12:28 AM
    Thursday, November 02, 2017 12:26 AM