0

I'm trying the following .vbs script to copy the first file from every folder to a new location in windows, but I'm not sure how to copy files that are nested 2 or 3 sub-folders deep. Can anyone help with this?

Const rootFolder = "c:\Rootfolder"
Const targetFolder = "c:\TargetFolder"

Set fso = CreateObject("Scripting.FileSystemObject")

For Each objFolder In fso.GetFolder(rootFolder).SubFolders
    i = 0
    For Each sFile In objFolder.Files
        If i = 0 then
            fso.GetFile(sFile).Copy targetFolder & "\" & fso.GetFileName(sFile),True
            i = 1
        End if
    Next
Next
Kyle
  • 9
  • 2

1 Answers1

2

You can define a function and call that function while looping the subfolders of your folder recursively

Const rootFolder = "c:\Rootfolder"
Const targetFolder = "c:\TargetFolder"

Set fso = CreateObject("Scripting.FileSystemObject")

dim folder
set folder = fso.GetFolder(rootFolder)

'call function from rootfolder
moveFirstFile folder

function moveFirstFile(folder)
    dim subFolder
    For Each subFolder In folder.SubFolders
        i = 0
        For Each sFile In subFolder.Files
            If i = 0 then
                fso.GetFile(sFile).Copy targetFolder & "\" & fso.GetFileName(sFile),True
                i = 1
            End if
        Next
        'move one level deeper
        moveFirstFile subFolder
    Next
end function
Geert Bellekens
  • 12,788
  • 2
  • 23
  • 50