Solved

NEED VBScript to copy entire directory

Posted on 2011-03-17
35
847 Views
Last Modified: 2012-08-13
Hi,

Can VBScript copy and entire directory and its subdirectory to a location?  and create the directory on the location if it doesn't exist and overwrite existing one if it does.  Not prompt etc.. Need it to copy entire directory it's subdirectories and all files etc.....

Can it handle target directory of:   \\lynx\backups\essbase\
0
Comment
Question by:elwayisgod
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 16
  • 13
  • 3
  • +3
35 Comments
 
LVL 6

Expert Comment

by:dave_it
ID: 35160289
Why not use Robocopy instead?
0
 
LVL 81

Expert Comment

by:zorvek (Kevin Jones)
ID: 35160297
The routine below copies files from one folder to another. Options are provided to specify a file filter, whether or not pre-existing files are to be replaced, and whether or not to copy sub folders.

[Begin Code Segment]

Public Function CopyFiles( _
      ByVal SourceFolder As String, _
      ByVal TargetFolder As String, _
      Optional ByVal FileNamePattern As String, _
      Optional ByVal Overwrite As Boolean, _
      Optional CopySubFolders As Boolean _
   ) As Long

' Copy all files in a folder to another folder. Returns the number of files
' copied.
'
' Syntax
'
' CopyFilesPattern(SourceFolder, TargetFolder, [FileNamePattern], [Overwrite])
'
' SourceFolder - The source folder path with or without the trailing backslash.
'
' TargetFolder - The target folder path with or without the trailing backslash.
'
' FileNamePattern - The pattern to use to find file names to copy. Optional. If
'   omitted then all files are copied.
'
' Overwrite - Pass True to overwrite pre-existing files in the target folder,
'   False to not overwrite files. Optional. If omitted then False is assumed.
'
' CopySubFolders - Pass True to include all sub folders, False otherwise.
'   Optional. If omitted then False is assumed.

   Dim FileName As Variant
   Dim FileNames As Collection
   Dim Count As Long
   
   If Right(SourceFolder, 1) <> "\" Then SourceFolder = SourceFolder & "\"
   If Right(TargetFolder, 1) <> "\" Then TargetFolder = TargetFolder & "\"
   If Len(FileNamePattern) = 0 Then FileNamePattern = "*.*"
   
   If Len(Dir(TargetFolder)) = 0 Then MkDir TargetFolder
   
   Set FileNames = New Collection
   FileName = Dir(SourceFolder & FileNamePattern)
   Do While Len(FileName) > 0
      If FileName <> "." And FileName <> ".." Then
         FileNames.Add FileName
      End If
      FileName = Dir
   Loop
   
   For Each FileName In FileNames
      If Len(Dir(TargetFolder & FileName)) > 0 And Overwrite Or Len(Dir(TargetFolder & FileName)) = 0 Then
         If Len(Dir(TargetFolder & FileName)) > 0 Then Kill TargetFolder & FileName
         FileCopy SourceFolder & FileName, TargetFolder & FileName
         Count = Count + 1
      End If
   Next FileName
   
   Set FileNames = New Collection
   If CopySubFolders Then
      FileName = Dir(SourceFolder & "*.*", vbDirectory)
      Do While Len(FileName) > 0
         If FileName <> "." And FileName <> ".." And GetAttr(SourceFolder & FileName) And vbDirectory Then
            FileNames.Add FileName
         End If
         FileName = Dir
      Loop
   End If
   
   For Each FileName In FileNames
      Count = Count + CopyFiles(SourceFolder & FileName, TargetFolder & FileName, FileNamePattern, Overwrite, CopySubFolders)
   Next FileName
   
   CopyFiles = Count

End Function

[End Code Segment]

Kevin
0
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35160372
You have to specifiy the full path for this, including drive.

dim FSO, rootdir, targdir

rootdir = Wscript.Arguments(0)
targdir = Wscript.Arguments(1)

set FSO = CreateObject("Scripting.FileSystemObject")

set TempDir = FSO.GetFolder(rootDir)
TempDir.Copy(targdir)

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35160383
Here's what I was working on  : )


You would need to make sure on "source" and "target" (at the head of the script) that you include the trailing slash.
source = "C:\tmp\"
target = "\\lynx\backups\essbase\"


SET fso = CreateObject("Scripting.FileSystemObject")

SET parent = fso.GetFolder(source)

CALL CopyRecursive(parent, target)




Sub CopyRecursive(directory, parentPath)
    For Each file in directory.Files
        CALL file.Copy(parentPath & file.Name, TRUE)
    Next
    
    For Each folder in directory.SubFolders
        path = parentPath & folder.Name
        CALL folder.Copy(path, TRUE)
        
        CALL CopyRecursive(folder, path & "\")
    Next
End Sub

Open in new window

0
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35160394
Comment about last post:

Copy the code to a file and call it CopyDirectory.vbs

Then, in a command prompt, execute:

CopyDirectory C:\myfolder C:\mynewfolder
0
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35160418
Sorry, let me put this all in one post!

Copy the code to a file and call it CopyDirectory.vbs

Then, in a command prompt, execute:

CopyDirectory C:\myfolder C:\mynewfolder


dim FSO, rootdir, targdir

rootdir = Wscript.Arguments(0)
targdir = Wscript.Arguments(1)

set FSO = CreateObject("Scripting.FileSystemObject")

set TempDir = FSO.GetFolder(rootDir)
TempDir.Copy(targdir) 
Toggle Highlighting

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35160422
@GeoffHarper

If I'm not mistaken, Folder.Copy() by itself only copies the folder--it does not copy contents.
0
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35160450
@kaufmed:

No, try it.  It copies the folder, folder contents, and any subfolders and their contents.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35160549
Hmmm....  So it does. I wonder why I remember having to write a recursive routine for this...   curiouser and curiouser.

Bravo  = )
0
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35160638
@kaufmed:

I've done the same thing with recursion and it's still valid if you need to exclude files, or put them in a Collection (list) or other such things.
0
 

Author Comment

by:elwayisgod
ID: 35161260
Robocopy is not installed on these servers.  I asked client and they said they might be able to oblige.
0
 
LVL 12

Expert Comment

by:prashanthd
ID: 35161462
Why not use XCOPY?

XCOPY sourcedir destinationdir /i /e
0
 

Author Comment

by:elwayisgod
ID: 35161564
xcopy chokes as the directories are really long....
0
 
LVL 4

Accepted Solution

by:
GeoffHarper earned 500 total points
ID: 35161577
So, this VBScript does not do the job for you, even if adapted?

I post it once more, cleaned up a bit:


Dim FSO, rootdir, targdir, tempdir 

If Wscript.Arguments.Count <> 2 Then
	Wscript.Echo "Usage: CopyDirectory.vbs {full source path} {full destination path}"
Else
	rootdir = Wscript.Arguments(0)
	targdir = Wscript.Arguments(1)
	Set FSO = CreateObject("Scripting.FileSystemObject")
	Set tempdir = FSO.GetFolder(rootDir)
	tempdir.Copy(targdir)
	Set tempdir = Nothing
End if

Open in new window

0
 

Author Comment

by:elwayisgod
ID: 35192986
Just getting to this now.  So my source directory is in directory  E:\TEMPFILES

Target directory is UNC path  \\backups\hyperion

Will that work?  If so, what is the proper way to put it in script above.  Not sure about parens etc...
0
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35193039
Yes, it should work.

BTW, in the future if you have spaces in folder names, you need double-quotes around the path(s).

copydirectory.vbs E:\TEMPFILES \\backups\hyperion
0
 

Author Comment

by:elwayisgod
ID: 35193056
This does not copy anything. Not sure I did it correctly

Dim FSO, rootdir, targdir, tempdir

If Wscript.Arguments.Count <> 2 Then
      Wscript.Echo "Usage: CopyDirectory.vbs {E:\LCM} {\\opus\hyperion\LCMTEST}"
Else
      rootdir = Wscript.Arguments(0)
      targdir = Wscript.Arguments(1)
      Set FSO = CreateObject("Scripting.FileSystemObject")
      Set tempdir = FSO.GetFolder(rootDir)
      tempdir.Copy(targdir)
      Set tempdir = Nothing
End if
0
 

Author Comment

by:elwayisgod
ID: 35193096
OK.  When I fire it off correctly:

cscript filecopy.vbs E:\LCM E:\LCMNEW

It does copy all the files to the target directory E:\LCMNEW

However, I need the target to be a SAN and UNC path.....Is that possible?
0
 

Author Comment

by:elwayisgod
ID: 35193105
If I map the drive it works ok too... but not sure mapping drive is best....
0
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35193138
Yes, it should be able to copy from/to UNC paths.
0
 

Author Comment

by:elwayisgod
ID: 35193139
your right it does work ok... is there a way to have it write to a .log file and show the files copied/progress?  not sure how to catch that in vb
0
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35193215
I don't think so.  That's not what you asked originally, so I gave you what you asked.  If you need to do things in-between each copy operation, then you need a routine that recurses directories.

See my comment above to kaufmed:

@kaufmed:

I've done the same thing with recursion and it's still valid if you need to exclude files, or put them in a Collection (list) or other such things.
0
 

Author Comment

by:elwayisgod
ID: 35193221
uh oh... so my actual source path is really long:

E:\apps\Hyperion\common\import_export\planadmin@Native Directory

When i use this not all folders are copied.. It just stops.. Perhaps is the length of the source dir and target dir come into play like in XCOPY?
0
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35193258
As I said earlier, "BTW, in the future if you have spaces in folder names, you need double-quotes around the path(s)."

copydirectory.vbs "E:\apps\Hyperion\common\import_export\planadmin@Native Directory" "your destination"
0
 

Author Comment

by:elwayisgod
ID: 35193285
Both are stopping at same point...

E:\Temp>call copy.bat >sam.log
E:\Temp\filecopy.vbs(10, 2) Microsoft VBScript runtime error: Path not found


E:\Temp>call copy.bat >sam.log
E:\Temp\filecopy.vbs(10, 2) Microsoft VBScript runtime error: Path not found


E:\Temp>call copy.bat >sam.log
E:\Temp\filecopy2.vbs(21, 9) Microsoft VBScript runtime error: Path not found


E:\Temp>call copy.bat >sam.log
E:\Temp\filecopy2.vbs(21, 9) Microsoft VBScript runtime error: Path not found


E:\Temp>ge
0
 

Author Comment

by:elwayisgod
ID: 35193292
I did that...
0
 

Author Comment

by:elwayisgod
ID: 35193317
So if the sub directories and files in the subdirectories of the original directory have spaces, is that where it's choking?
0
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35193342
Yes.

Can you attach copy.bat?
0
 

Author Comment

by:elwayisgod
ID: 35193469
So I started digging into the full subdirs where it chokes.  This directory below is 208 Characters.  I holds 9 .xml files.  Two of which are 59 chars and 51 chars for totals of 267 chars and 259 chars.  The next longest file in this directory is 48 chars for total of 256 chars and it copies fine.  Thus something about going over 256 chars?

E:\apps\Hyperion\common\import_export\planadmin@Native Directory\TS_EMBUD\resource\Plan Type\EMBUDGET\Data Forms\2.0 Current Forecast Data Input and Review\2.4 Purchase Power Review\2.4.2 Basin Purchase Power
0
 

Author Comment

by:elwayisgod
ID: 35193509
I apologize this is going further.  I'll bump up points.  Is there a way to avoid this 256 char limit?
0
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35193559
Wow, it looks like that's your problem.

I don't have any quick suggestions to it.

This has been discussed on the following post: http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Server/2003_Server/Q_22750265.html
0
 

Author Comment

by:elwayisgod
ID: 35193573
Does Robocopy solve this?
0
 

Author Comment

by:elwayisgod
ID: 35193633
0
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35193654
According to that link, it looks like it may solve your problem.
0
 

Author Comment

by:elwayisgod
ID: 35193699
Thanks for help.. I thought maybe VB could bypass the limit too :)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
This article is the result of a quest to better understand Task Scheduler 2.0 and all the newer objects available in vbscript in this version over  the limited options we had scripting in Task Scheduler 1.0.  As I started my journey of knowledge I f…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question