Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to create sub-folders

Status
Not open for further replies.

tbscmgi

MIS
Sep 17, 2003
66
US
I'm trying to copy files from
//is/prod TO //is/backup/prod
under the prod folder there are sub-folders.
When I try to copy I keep getting error path not found, and that because I don't have those sub-folderd created under the backup/prod folder. Is there anyway to make those sub-folder during the copy?

Thanks
 
Why don't you use a tool like RoboCopy??

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
my company don't want to use third party software
 
Even if it is made by Microsoft??

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
If you don't want to use RoboCopy, how are you currently copying those files over?? Where is the script you're using for this? Maybe copy the folder over instead of the individual files??

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
'=========================== G l o b e A r e a ==============================
'
dim sctr, fctr, cctr, c
dim mfr, MFile, EFile, NFile, MasterDict
dim wefp, dt, TInfo, FInfo, PInfo
'
'
'============================================================================
'
' S h o w O p e n i n g O u t p u t F i l e
' =========================================
'
Sub ShowOpeningOutputFile

set MFile = objFSO.OpenTextFile("\\isd\cashiering\DP500Mmasterfile.txt", 2, true)
set EFile = objFSO.OpenTextFile("\\isd\cashiering\DP500Emasterfile.txt", 2, true)
set NFile = objFSO.OpenTextFile("\\isd\cashiering\DP500Nmasterfile.txt", 2, true)

End Sub
'============================================================================
'
'
Sub TRecurseFolder(objFSO, strFolderPath)
Dim objFolder : Set objFolder = objFSO.GetFolder(strFolderPath)

Dim objFile

For Each objFile In objFolder.Files
TInfo = Ucase(strFolderPath & "~" & objFile.Name & "~" & objFile.DateLastModified & "~" & objFile.Size)
MFile.WriteLine Ucase(Right(TInfo,(Len(TInfo)-24)))
If MasterDict.Exists(Ucase(Right(TInfo,(Len(TInfo)-24)))) Then
msgbox "Load Already Exists = " & Ucase(Right(TInfo,(Len(TInfo)-24)))
Else
MasterDict.Add Ucase(Right(TInfo,(Len(TInfo)-24))), Ucase(Right(TInfo,(Len(TInfo)-24)))
fctr = fctr + 1
End If
Next

Dim objSubFolder
For Each objSubFolder In objFolder.SubFolders
TRecurseFolder objFSO, objSubFolder.Path
Next
End Sub
'============================================================================
'
'
Sub FRecurseFolder(objFSO, strFolderPath)
Dim objFolder : Set objFolder = objFSO.GetFolder(strFolderPath)

Dim objFile

For Each objFile In objFolder.Files
FInfo = Ucase(strFolderPath & "~" & objFile.Name & "~" & objFile.DateLastModified & "~" & objFile.Size)
PInfo = Ucase(strFolderPath & "\" & objFile.Name) & " "
If MasterDict.Exists(Ucase(Right(FInfo,(Len(FInfo)-12)))) Then
sctr = sctr + 1
EFile.WriteLine Ucase(Right(FInfo,(Len(FInfo)-12)))
else
cctr = cctr + 1
NFile.WriteLine Ucase(Right(FInfo,(Len(FInfo)-12)))
FCT = "\\isd\cashiering\backup\" & Ucase(Right(PInfo,(Len(PInfo)-12)))
msgbox "path = " & PInfo & " " & FCT
objFSO.CopyFolder PInfo , FCT , True

End If
Next

Dim objSubFolder
For Each objSubFolder In objFolder.SubFolders
FRecurseFolder objFSO, objSubFolder.Path
Next
End Sub
'==============================================================================
'
' < < < < M a i n S t r e a m > > > >
' ===================================
'
'
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set MasterDict = CreateObject("Scripting.Dictionary")
MasterDict.CompareMode = VBTextCompare
'
'
' < < < < C a l l T o S u b > > > >
' ===================================
'
'
'
' c a l l i n g S h o w O p e n i n g O u t p u t F i l e
' -----------------------------------------------------------
'
'
call ShowOpeningOutputFile
'
'
'
' T o R e c u r s e F o l d e r
' -------------------------------
'
'
TRecurseFolder objFSO, "\\isd\cashiering\Backup\"
'
'
' c l o s i n g M a s t e r t e x t f i l e
' --------------------------------------------
'
'
MFile.Close
'
'
' F r o m R e c u r s e F o l d e r
' -----------------------------------
'
'
FRecurseFolder objFSO, "\\isd-track\Images\"
FRecurseFolder objFSO, "\\isd-track\Prod\"
'
'
msgbox "End File Copy " & "master dict count = " & fctr
msgbox "End File Copy " & "found dict count = " & sctr
msgbox "End File Copy " & "new dict count = " & cctr
 
I agree with using robocopy. It is very easy to script it and it is a Microsoft utility. It is even included in the OS now starting with Vista.

ROBOCOPY Source Destination /MIR

Will mirror the directory structure from source to destination. Super easy!

I hope you find this post helpful.

Regards,

Mark

Check out my scripting solutions at
Work SMARTER not HARDER. The Spider's Parlor's Admin Script Pack is a collection of Administrative scripts designed to make IT Administration easier! Save time, get more work done, get the Admin Script Pack.
 
I still say RoboCopy...you can save time by having it only copy those files that have actually been changed...but if you insist on your code....well...you lost me there a bit. The following sub may help you build a path.

Code:
Option Explicit

BuildPath "C:\temp\dir1\dir2\dir3\dir4\dir5"

Sub BuildPath(strDirPath)
	Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
	Dim arrPath : arrPath = Split(strDirPath, "\")
	Dim intElemCount, strPath : strPath = arrPath(0)
	For intElemCount = 1 To UBound(arrPath)
		strPath = strPath & "\" & arrPath(intElemCount)
		If Not objFSO.FolderExists(strPath) Then objFSO.CreateFolder strPath
	Next
End Sub

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
Funny enough I came across one yesterday

Code:
'-----------------------------------
' ========================================
' TITLE:        	CopyFolderStructure
'
' PURPOSE:  		Copy the content of a folder to another one.
'					Everything from the source folder and all subfolders
'					will be copied in folder choosen by the user. All files in each
'					folder/subfolders will be copied also, except if you want exclude
'					some files group as exe, com, hta or any other extension. In that Case
'					all files will be copied except what is in strExcludedExt
'
' PARAMETERS:		strSource = source directory for web images to copy.
'					strDestination = destination folder for web images.
'					strExcludedExt = file extension to exclude from being copied.
'									 Could have more than one extension excluded.
'									 Make sure to separate each extension by a comma (,).
'
' HOW TO USE:		Call CopyFolderStructure(strSourceFolder, strSubFolder, ["exe" or "" or "exe,zip"])
'
' NOTES:			I declared objFSO globally outside Function/Sub to avoid creating
'					object each time it is invoked through recursive calls. It could be
'					included in CopyFolderStructure if you prefer.
' =============================================
Option Explicit
Dim objFSO, strSourceFolder, strDestFolder, strExclusion, strPrompt

Set objFSO = CreateObject("Scripting.FileSystemObject")
strSourceFolder = BrowseForFolderDialogBox("Choose a root folder to copy.")
strDestFolder = BrowseForFolderDialogBox("Choose the destination folder to copy source folder in.")
strPrompt = "Type extension to exclude to be copied from source to destination. " _
			& "Separate each of them by a comma (,). If there is no extension to exclude, " _
			& "live this box blank."
strExclusion = InputBox(strPrompt, "Choose extension to exclude", "exe,zip")
If IsNoData(strExclusion) Then strExclusion = ""	'Make sure it is blank.
'Call function that will copy folder structure as well as files in it.
CopyFolderStructure strSourceFolder, strDestFolder, strExclusion

Function CopyFolderStructure(strSource, strDestination, strExcludedExt)
	Const OVER_WRITE_FILES = True
	Dim objDir, objFolder, objFiles, strCurExt, intX, arrExt, blnExclude
	
	'Connect to the current directory in strSource.
	Set objDir = objFSO.GetFolder(strSource)
	
	'If current folder doesn't exist under destination folder, create it.
	 If Not objFSO.FolderExists(strDestination & "\" & objDir.Name) Then
		objFSO.CreateFolder(strDestination & "\" & objDir.Name)
	End If
	'Validate if there is something in strExcludedExt.
	If Not IsNoData(strExcludedExt) Then
		'If yes, transfer content from strExcludedExt in an array.
		arrExt = Split(strExcludedExt, ",")
		blnExclude = False		'Intialize to False blnExclude
	End If
	'Loop through all files in current folder if any and copy all files in destination folder
	'except for excluded extension if any in strExcludedExt.
	For Each objFiles In objFSO.GetFolder(strSource).Files
		'If there is exclusion, will compare if current extension file is excluded or not.
		If Not IsNoData(strExcludedExt) Then
			strCurExt = objFSO.GetExtensionName(objFiles.Name)	'Take current extension.
			'Loop through the array to find if current extension has to be copied or not.
			For intX = 0 To UBound(arrExt)
				If LCase(strCurExt) = arrExt(intX) Then
					blnExclude = True	'If found, set to True blnExclude and exit for.
					Exit For
				Else
					blnExclude = False
				End If
			Next
			If Not blnExclude Then	'If blnExclude is True, current file will not be copied.
				objFSO.CopyFile strSource & "\" & objFiles.Name, strDestination & "\" & objDir.Name & "\" & objFiles.Name, OVER_WRITE_FILES
			End If
		Else	'If no exclusion, copy everything in all folders/subfolders
			objFSO.CopyFile strSource & "\" & objFiles.Name, strDestination & "\" & objDir.Name & "\" & objFiles.Name, OVER_WRITE_FILES
		End If
	Next
	' If there is subfolder(s) under current folder in strPath, Call
	' recursively this sub until there is no other subfolder(s)
	For Each objFolder In objFSO.GetFolder(strSource).SubFolders
		CopyFolderStructure objFolder.Path, strDestination & "\" & objDir.Name, strExcludedExt
	Next
End Function
'--------------------------------------------------
' =================================================
' TITLE:        	BrowseForFolderDialogBox
'
' PURPOSE:		  	Open Window dialog box to choose directory to process.
'					Return the choosen path to a variable.
'
' HOW TO USE:		strResult = BrowseForFolderDialogBox()
' ====================================================
Function BrowseForFolderDialogBox(strTitle)
	Const WINDOW_HANDLE = 0
	Const NO_OPTIONS = &H0001
	Dim objShellApp
	Dim objFolder
	Dim objFldrItem
	Dim objPath
	
	Set objShellApp = CreateObject("Shell.Application")
	Set objFolder = objShellApp.BrowseForFolder(WINDOW_HANDLE, strTitle , NO_OPTIONS)
	If IsNoData(objFolder) Then
		WScript.Echo "You choose to cancel. This will stop this script."
		Wscript.Quit
	Else
		Set objFldrItem = objFolder.Self
		objPath = objFldrItem.Path
		BrowseForFolderDialogBox = objPath
		Set objShellApp	= Nothing
		Set objFolder	= Nothing
		Set objFldrItem	= Nothing
	End If
End Function
'---------------------------------------------------
' ==================================================
' TITLE:        	IsNoData
'
' PURPOSE:		  	Verify if passed parameter variable contain something.
'
' RETURN:			True if contain something, otherwise, False.
'
' HOW TO USE:		intResult = IsNoData(varSource) or
'					If IsNoData(varSource) Then do something.
' ====================================================
Function IsNoData(varVal2Check)
	'Verify if varVal2Check contain something.
	On Error Resume Next
    If IsNull(varVal2Check) Or IsEmpty(varVal2Check) Then
		IsNoData = True
    Else
        If IsDate(varVal2Check) Then
			IsNoData = False
        Elseif varVal2Check = "" Then
			IsNoData = True
		ElseIf Not IsObject(varVal2Check) Then
			IsNoData = False
		Else
            IsNoData = False
        End If
    End If
End Function
 
or you could use this

Code:
'=======================================================
'
'  Script: VBScript Backup & Sync
'    Date: 04/17/2006
'  Author: Michael J. Damato
' Contact: mjdamato@cox.net
'
'   Notes: This is still in development
'=======================================================
Option Explicit 

'Create needed variables
Dim objNetwork, objFSO, RegExObj, variablesObj
Dim SOURCE, TARGET, FLDR_EXcLUDE, FILE_EXCLUDE
Dim replicate, synchronize, silent, hiddenFiles, hiddenFldrs
Dim sourceObj, subSourceObj, sourceFileObj, sourceFile, newSource
Dim targetObj, subTargetObj, targetFileObj, targetFile, newTarget
Dim WshShell, sUserName, WshEnv

Set WshShell = WScript.CreateObject("WScript.Shell")
Set objNetwork = wscript.CreateObject("wscript.network") 'objNetwork.Username
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set variablesObj = WScript.Arguments
Set WshEnv = WshShell.Environment("Process")

'=======================================================
'=============== USER DEFINED VARIABLES ================
'=======================================================
sUserName = WshEnv("%USERPROFILE%") 'Could use sUserName = WshNetwork.UserName
SOURCE = sUserName & "\My Documents"
TARGET = "D:\My Documents"

'Excluded folders
'- list folder names, comma separated
FLDR_EXcLUDE = ""

'Excluded file types
'- list file extensions (without periods), comma separated
FILE_EXCLUDE = ""		'exe,txt
'****************************************************************************************************
'Replication
'1. Starts with source folder and if it doesn't exist on the target copies it and all contents there
'2. If the source folder does exist on the target it checks the files in that folder and copies any missing files or files with later modified dates to the target
'3. Recurses through all subfolders (all levels) in the source, repeating steps 1 & 2 for each

'Synchronization
'4. Starts with target folder and if it does not exist in the source deletes it.
'5. If the target folder does exist in source it goes through all files in the target folder and deletes them if they do not exist in the source
'6. Recurses through all sub folders (all levels) in the target, repeating steps 4 & 5 for each.
'****************************************************************************************************

replicate   = true     'Perform replication: true/false
synchronize = false    'Perform synchonization: true/false
silent      = false    'Show dialogs: true false
hiddenFldrs = true     'Process hidden folders: true/false
hiddenFiles = true     'Process hidden files: true/false
'       NOTE: If a folder is missing in the target, the entire
'             folder is copied, even the hidden files
'=======================================================

'Use variables passed from command line if sent
If WScript.Arguments.Count > 0 Then
  replicate = variablesObj(0)
End If
If WScript.Arguments.Count > 1 Then
  synchronize = variablesObj(1)
End If
If WScript.Arguments.Count > 2 Then
  silent = variablesObj(2)
End If

'Set up regular expression object
Set RegExObj = New RegExp
RegExObj.IgnoreCase = True
FILE_EXCLUDE = "," & FILE_EXCLUDE & ","
FLDR_EXCLUDE = "," & FLDR_EXCLUDE & ","

'Verify if source folder exists
If Not (objFSO.FolderExists(SOURCE)) Then
  'Do not replicate, Perform error handling
  If Not ( silent ) Then
    MsgBox "Source Missing"
  End If
'Proceed if replicating is on
ElseIf ( replicate ) Then
    replicateFolders SOURCE, TARGET
End If

'Verify if target folder exists
If Not (objFSO.FolderExists(TARGET)) Then
  'Do not synchronize, Perform error handling
  If Not ( silent ) Then
    MsgBox "Target Missing"
  End If
'Proceed if synching is on
ElseIf ( synchronize ) Then
    syncFolders SOURCE, TARGET
End If

'Cleanup variables
Set objFSO        = nothing
Set objNetwork    = nothing
Set variablesObj  = nothing
Set RegExObj      = nothing
Set sourceObj     = nothing
Set targetObj     = nothing
Set targetFileObj = nothing
Set sourceFileObj = nothing

If Not ( silent ) Then
  MsgBox "Backup Complete!", 0, "Done"
End If

'=======================================================
Sub replicateFolders (currentSource, currentTarget)
'=======================================================
'This procedure will call the procedure replicateFiles
'to process the files in the current directory. Then it
'will check the subfolders in the current directory. If
'a sub directory does not exist in the target it will be
'copied there. If it does exist the procedure will
'perform replicateSource on that directory as well
'=======================================================

  'Check if target folder exists
  If Not (objFSO.FolderExists(currentTarget)) Then

    'Create the target folder and copy the contents of currentSource there
    objFSO.CreateFolder(currentTarget)
    objFSO.CopyFolder currentSource, currentTarget

  Else

    'Create folder object of the currentSource
    Set sourceObj = objFSO.GetFolder(currentSource)

    'Perform file replication for the currentSource
    replicateFiles sourceObj, currentTarget

    'Do recursive processing of sub folders
    For Each subSourceObj in sourceObj.SubFolders
      If Not excluded(subSourceObj.Name,0,FLDR_EXCLUDE) Then
      If (hiddenFldrs) Or (Not subSourceObj.Attributes And 2) Then
        newTarget = TARGET & RIGHT(subSourceObj.Path,(Len(subSourceObj.Path)-Len(SOURCE)))
        replicateFolders subSourceObj.path, newTarget
      End If
      End If
    Next

  End If

'=======================================================
End Sub 'replicateFolders
'=======================================================
'=======================================================
Sub replicateFiles (sourceObj, targetPath)
'=======================================================
  ' Recurse through all files in the source object
  For Each sourceFileObj in sourceObj.Files

    If Not excluded(sourceFileObj.Name,1,FILE_EXCLUDE) Then
    If (hiddenFiles) Or (Not sourceFileObj.Attributes And 2) Then
     targetFile = targetPath & "\" & sourceFileObj.Name

      'Check if file exists in target
      If objFSO.FileExists(targetFile) Then

        'Create file object of target file
        Set targetFileObj = objFSO.GetFile(targetFile)

        'Check if file in source is newer
        If sourceFileObj.DateLastModified > targetFileObj.DateLastModified Then
          'Overwrite existing file in target with newer source file
          sourceFileObj.Copy targetFile, true
        End If
      Else
        'Copy file from source to target
        sourceFileObj.Copy targetFile
      End If
    End If
    End If
  Next

'=======================================================
End Sub 'replicateFiles
'=======================================================
'=======================================================
Sub syncFolders (currentSource, currentTarget)
'=======================================================

  'Check if source folder exists
  If Not (objFSO.FolderExists(currentSource)) Then

    'Delete the current target folder
    objFSO.DeleteFolder currentTarget
  Else

    'Create folder object of the currentTarget
    Set targetObj = objFSO.GetFolder(currentTarget)
    'Perform file synching for the currentTarget
    syncFiles currentSource, targetObj

    'Do recursive processing of sub folders
    For Each subTargetObj in targetObj.SubFolders
      If Not excluded(subTargetObj.Name,0,FLDR_EXCLUDE) Then
      If (hiddenFldrs) Or (Not subTargetObj.Attributes And 2) Then
        newSource = SOURCE & RIGHT(subTargetObj.Path,(Len(subTargetObj.Path)-Len(TARGET)))
        syncFolders newSource, subTargetObj.path
      End If
      End If
    Next
  End If
'=======================================================
End Sub 'syncFolders
'=======================================================
'=======================================================
Sub syncFiles (sourcePath, targetObj)
'=======================================================
'=======================================================-
  ' Recurse through all files in the target object
  For Each targetFileObj in targetObj.Files

    'Do not process excluded file types
    If Not excluded(targetFileObj.Name,1,FILE_EXCLUDE) Then
      sourceFile = sourcePath & "\" & targetFileObj.Name

      'Delete target file if does not exist in source
      If Not (objFSO.FileExists(sourceFile)) Then
        targetFileObj.Delete true
      End If
    End If
  Next
'=======================================================
End Sub 'syncFiles
'=======================================================
Function excluded (itemName,isFile,excludeList)
'=======================================================
' Test if itemName is in excluded list
'=======================================================-
  'If file, get the file extension
  If isFile Then
    itemName = Right(itemName,Len(itemName)-InStrRev(itemName,"."))
  End If

  RegExObj.Pattern = "," & itemName & ","
  excluded = RegExObj.Test(excludeList)
'=======================================================
End Function 'excluded
'=======================================================
 
I give my vote to RoboCopy too. It's part of the Windows Server 2003 Resource Kit Tools, so it's hardly a third party app.

It's a very powerful command line utility, there's no install just copy it to your hard drive. They have now developed a GUI front end to help you generate the command line switches.

I use it in loads of script to replicate data from our central store to site servers, the initial copy takes a while, but then robocopy can then compare files and determine whether a file needs to be copied or is already on the target.

As already mentioned the /MIR (mirror) option will duplicate your source folder and all it's contents onto a new folder, files or folders that get deleted on the source, are deleted on the target too.
 
I don't see why peoples and in particular members of vbscript forum have to vote and overzealously promo robocopy. Doing folder/file copy using fso homogenously integrated in vbs is absolutely legitimate and is the prime choice. If people think robo can do something quicker and easier, by all mean use it. Using fso in some task may require more skill; using utility may be more commode, that's all.
 
I agree with what you are saying tsuji, but my guess is that the OP does not know how to use the fso properties and methods.

Robocopy will greatly simplify this process for the user. Instead of having to write code to check file versions to avoid unnecessary copy time Robocopy can do all that.

I hope you find this post helpful.

Regards,

Mark

Check out my scripting solutions at
Work SMARTER not HARDER. The Spider's Parlor's Admin Script Pack is a collection of Administrative scripts designed to make IT Administration easier! Save time, get more work done, get the Admin Script Pack.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top