VBScript FileSystemObject.Copyfolder and FileSystemObject.CreateFolder

d4rkcell picture d4rkcell · May 22, 2014 · Viewed 10.2k times · Source

apologies if this has been answered elsewhere. I am struggling to understand poor written English on other forum posts and I really want to understand what is going on.

This code works great.

dim FileSys, source, destination, WSNet, theDate, theTime, computerName

Set FileSys = CreateObject("Scripting.FileSystemObject")
Set WSNet = CreateObject("WScript.Network")

computerName = WSNet.computerName
theDate = Replace(Date, "/","-")
theTime = Replace(Time, ":",".")
source = "C:\source"
destination = "C:\destfolder"

if Not FileSys.FolderExists(destination) Then
  WScript.echo "the destination: " & destination & " doesnt exist, it will now be created"
  FileSys.Createfolder(destination)
  FileSys.CopyFolder source, destination
Else
  If FileSys.FolderExists(source) Then 
    FileSys.CopyFolder source, destination 
  Else
    WScript.echo "ERROR: The source folder is not present, nothing will be copied"
  End If 
End If

Yet when I replace this line:

destination = "C:\destfolder"

with somthing like this:

destination = "C:\destfolder\" & computerName & "\" & theDate & "\" & theTime

I get an error along the lines of. "Path Not Found" even if I narrow it down and use:

destination = "C:\destfolder\" & computerName

I get the same error. On the WScript.echo lines the string appears as I would expect e.g.

C:\destfolder\MYPC\22-05-2014\13.55.44

It doesn't seem to be creating folder, the problem seems to be around the FileSys.CreateFolder method, can anyone help?

PS - My overall goal here is to copy some log files from one place to another but order them by date and time by folder names.

Answer

aphoria picture aphoria · May 22, 2014

The CreateFolder method can only create a folder one level deep.

You will need to do something like this (this is just an example...lots of room for improvement):

destination = "C:\destfolder"
FileSys.Createfolder(destination)
FileSys.Createfolder(destination & "\" & computerName)
FileSys.Createfolder(destination & "\" & computerName & "\" & theDate)
FileSys.Createfolder(destination & "\" & computerName & "\" & theDate & "\" & theTime)

Or, you could create a function that will create multiple folders deep at a time. Here is an example of a function that does that.