• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 923
  • Last Modified:

NEED VBScript to copy entire directory

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
elwayisgod
Asked:
elwayisgod
  • 16
  • 13
  • 3
  • +3
1 Solution
 
dave_itCommented:
Why not use Robocopy instead?
0
 
zorvek (Kevin Jones)ConsultantCommented:
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
 
GeoffHarperCommented:
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
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
käµfm³d 👽Commented:
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
 
GeoffHarperCommented:
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
 
GeoffHarperCommented:
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
 
käµfm³d 👽Commented:
@GeoffHarper

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

No, try it.  It copies the folder, folder contents, and any subfolders and their contents.
0
 
käµfm³d 👽Commented:
Hmmm....  So it does. I wonder why I remember having to write a recursive routine for this...   curiouser and curiouser.

Bravo  = )
0
 
GeoffHarperCommented:
@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
 
elwayisgodAuthor Commented:
Robocopy is not installed on these servers.  I asked client and they said they might be able to oblige.
0
 
prashanthdCommented:
Why not use XCOPY?

XCOPY sourcedir destinationdir /i /e
0
 
elwayisgodAuthor Commented:
xcopy chokes as the directories are really long....
0
 
GeoffHarperCommented:
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
 
elwayisgodAuthor Commented:
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
 
GeoffHarperCommented:
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
 
elwayisgodAuthor Commented:
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
 
elwayisgodAuthor Commented:
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
 
elwayisgodAuthor Commented:
If I map the drive it works ok too... but not sure mapping drive is best....
0
 
GeoffHarperCommented:
Yes, it should be able to copy from/to UNC paths.
0
 
elwayisgodAuthor Commented:
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
 
GeoffHarperCommented:
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
 
elwayisgodAuthor Commented:
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
 
GeoffHarperCommented:
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
 
elwayisgodAuthor Commented:
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
 
elwayisgodAuthor Commented:
I did that...
0
 
elwayisgodAuthor Commented:
So if the sub directories and files in the subdirectories of the original directory have spaces, is that where it's choking?
0
 
GeoffHarperCommented:
Yes.

Can you attach copy.bat?
0
 
elwayisgodAuthor Commented:
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
 
elwayisgodAuthor Commented:
I apologize this is going further.  I'll bump up points.  Is there a way to avoid this 256 char limit?
0
 
GeoffHarperCommented:
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
 
elwayisgodAuthor Commented:
Does Robocopy solve this?
0
 
GeoffHarperCommented:
According to that link, it looks like it may solve your problem.
0
 
elwayisgodAuthor Commented:
Thanks for help.. I thought maybe VB could bypass the limit too :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 16
  • 13
  • 3
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now