Announcement

Collapse
No announcement yet.

VBS - CreateFolder with sub-dir's (recursion)

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • VBS - CreateFolder with sub-dir's (recursion)

    I am having trouble writing a VBScript that will create a Folder with sub-directories (i.e. C:\Folder1\Folder2 where Folder1 does not yet exist). I know that I have to write a recursive method or loop. I have found many examples online but can't seem to get any of them to work for me. Below is an example of what I would like to expand.

    Code:
    If Not objFSO.FolderExists("C:\Folder1\Folder2\") then
         objFSO.CreateFolder("C:\Folder1\Folder2\")
    End if
    As always, thanks in advance.

  • #2
    Re: VBS - CreateFolder with sub-dir's (recursion)

    I will work on an issue for days before posting, and without fail, I will find something minutes after I post. Anyway, I found this little gem and it does work. Having said that, it seems way to verbose. There has to be a cleaner shorter way to do this.

    Code:
    Set oShell = CreateObject("WScript.Shell")
    oSYSDRIV = oShell.Environment("Volatile").Item ("SYSTEMDRIVE")
    WOPM = oSYSDRIV & "\Prometheus\WOPM"
    
    '// a normal function
    Call CreateDirectoryPath(WOPM)
    
    '// a recursion function
    Call Recursion(WOPM)
    
    Function CreateDirectoryPath(DirPath)
    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    If objFSO.FolderExists(DirPath) Then
    Exit Function
    End If
    
    aDirectories = Split(DirPath, "\")
    sCreateDirectory = aDirectories(0)
    For iDirectory = 1 To UBound(aDirectories)
    sCreateDirectory = sCreateDirectory & "\" & aDirectories(iDirectory)
    If Not objFSO.FolderExists(sCreateDirectory) Then
    	objFSO.CreateFolder(sCreateDirectory)
    End If
    Next
    End Function
    
    Function Recursion(DirectoryPath)
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    
    If objFSO.FolderExists(DirectoryPath) Then Exit Function
    Call Recursion(objFSO.GetParentFolderName(DirectoryPath))
    objFSO.CreateFolder(DirectoryPath)
    End Function
    Last edited by CaTBuS; 29th June 2011, 14:35.

    Comment

    Working...
    X