Vbscript: move files based on extension v2

Hello experts,
I have the following vbscript that help me to move files based on extension.
I got an out of memory error message when I launch the script and one of the reported folder doesn't exist.
I think the makedir function needed to be adjusted but I don't know how to proceed.
' ==============================================================================
' C O N S T A N T S   &   V A R I A B L E S
' ==============================================================================

' Define needed constants
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const TriStateUseDefault = -2

' Specify path to folder of files to process, default destination, and log file
strScriptDir = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
strBaseDir = strScriptDir
strLogFile = strScriptDir & "\log-file.log"

' ==============================================================================
' I N I T I A L I Z A T I O N
' ==============================================================================

' Create filesystem object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Open log file (append)
Set objLogFile = objFSO.OpenTextFile(strLogFile, ForWriting, True)

' Make sure base directory exists
If Not objFSO.FolderExists(strBaseDir) Then
    objLogFile.WriteLine Now() & " *ERROR* Base directory does not exist """ & strBaseDir & """"
    Wscript.Quit()
End If

' Create a dictionary to hold the list of extensions to move, and destination folders
Set dicExt = CreateObject("Scripting.Dictionary")
dicExt.CompareMode = vbTextCompare

' Add the extensions to the dictionary, and the destination folders
dicExt.Add "pdf",strBaseDir & "\Pdf"
dicExt.Add "xls", strBaseDir & "\Xl"
dicExt.Add "xlsx",strBaseDir & "\Xl"
dicExt.Add "xlsm",strBaseDir & "\Xl"
dicExt.Add "txt",strBaseDir & "\Txt"
dicExt.Add "pptx",strBaseDir & "\Ppt"
dicExt.Add "doc",strBaseDir & "\Doc"
dicExt.Add "docx",strBaseDir & "\Doc"
dicExt.Add "exe",strBaseDir & "\Exe"
dicExt.Add "zip",strBaseDir & "\Zip"
dicExt.Add "png",strBaseDir & "\Png"

'dicExt.Add "txt",strBaseDir & "\Txt"
' ==============================================================================
' M A I N   L O G I C
' ==============================================================================

' Process each file in the base folder
Set objBaseDir = objFSO.GetFolder(strBaseDir)
For Each objFile In objBaseDir.Files
    ProcessFile objFile
Next    

' ==============================================================================
' W R A P U P
' ==============================================================================

' Done, cleanup and exit
objFile.Close
objLogFile.Close
Wscript.Quit

' ==============================================================================
' S U B R O U T I N E S   &   F U N C T I O N S
' ==============================================================================


Sub ProcessFile(objFile)
    ' Process a file, first get extension
    strExt = objFSO.GetExtensionName(objFile.Path)

    ' If exists in defined extensions with destination folders use that folder, else use default
    If dicExt.Exists(strExt) Then
        strMoveToDir = dicExt.Item(strExt)
    End If

    ' Create the destination folder if needed
    If Not objFSO.FolderExists(strMoveToDir) Then
        objLogFile.WriteLine Now() & " *WARNING* Creating destination directory """ & strMoveToDir & """"
        MakeDir strMoveToDir
    End If

    ' Move the file
    objLogFile.WriteLine Now() & " *INFO* Moving file """ & objFile.Name & """ to directory """ & strMoveToDir & """"
    objFile.Move strMoveToDir & "\" & objFile.Name
End Sub

Sub MakeDir(ByVal strPath)
    ' Small recursive function to create a folder (and all parent folders in path if needed)
    If Not objFSO.FolderExists(strPath) Then
        ' Make sure parent of this folder exists first
        MakeDir objFSO.GetParentFolderName(strPath)
        ' Now create this folder
        objFSO.CreateFolder strPath
    End If
End Sub

Open in new window

Thank you in advance for your help.
LVL 1
LD16Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ste5anSenior DeveloperCommented:
Your MakeDir is a recursive function without correct termination handling I guess. Thus adding appropriate error handling should help:

Sub MakeDir(ByVal strPath)
  On Error Resume Next

  Err.Clear
  If Not FolderExists(strPath) Then
    ParentFolder = FolderGetParentName(strPath)
    If Len(ParentFolder) > 0 Then
      MakeDir ParentFolder
      FolderCreate strPath
    End If
  End If
End Sub

Sub FolderCreate(AFolder)
  On Error Resume Next

  Err.Clear
  objFSO.CreateFolder AFolder
  If Err.Number > 0 Then
    WScript.Echo "FolderCreate('" & AFolder & "'): " & Err.Description
    Err.Clear
  End If
End Sub

Function FolderExists(AFolder)
  On Error Resume Next

  Err.Clear
  FolderExists = objFSO.FolderExists(AFolder)
  If Err.Number > 0 Then
    WScript.Echo "FolderExists('" & AFolder & "'): " & Err.Description
    Err.Clear
  End If
End Function

End Function FolderGetParentName(AFolder)
  On Error Resume Next

  Err.Clear
  FolderGetParentName = objFSO.GetParentFolderName(AFolder)
  If Err.Number > 0 Then
    WScript.Echo "FolderGetParentName('" & AFolder & "'): " & Err.Description
    Err.Clear
  End If
End Function

Open in new window

LD16Author Commented:
Thank you for your proposal.
I tested but I got an error message in line 36. I remove "End" string however I am getting something strange with make dir folder.
29-Apr-19 2:49:23 PM *WARNING* Creating destination directory ""

Open in new window

I don't understand why the procedure report a blank folder for the creation.
Additionally I got permission denied and in the log:
29-Apr-19 2:49:23 PM *INFO* Moving file "29104964_move-files-based-on-location.vbs" to directory ""

Open in new window


Thought vbs. extension is not reported in files to move.

Here is my version:
' ==============================================================================
' C O N S T A N T S   &   V A R I A B L E S
' ==============================================================================

' Define needed constants
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const TriStateUseDefault = -2

' Specify path to folder of files to process, default destination, and log file
strScriptDir = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
strBaseDir = strScriptDir
strLogFile = strScriptDir & "\log-file.log"

' ==============================================================================
' I N I T I A L I Z A T I O N
' ==============================================================================

' Create filesystem object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Open log file (append)
Set objLogFile = objFSO.OpenTextFile(strLogFile, ForWriting, True)

' Make sure base directory exists
If Not objFSO.FolderExists(strBaseDir) Then
    objLogFile.WriteLine Now() & " *ERROR* Base directory does not exist """ & strBaseDir & """"
    Wscript.Quit()
End If

' Create a dictionary to hold the list of extensions to move, and destination folders
Set dicExt = CreateObject("Scripting.Dictionary")
dicExt.CompareMode = vbTextCompare

' Add the extensions to the dictionary, and the destination folders
dicExt.Add "pdf",strBaseDir & "\Pdf"
dicExt.Add "xls", strBaseDir & "\Xl"
dicExt.Add "xlsx",strBaseDir & "\Xl"
dicExt.Add "xlsm",strBaseDir & "\Xl"
dicExt.Add "txt",strBaseDir & "\Txt"
dicExt.Add "pptx",strBaseDir & "\Ppt"
dicExt.Add "doc",strBaseDir & "\Doc"
dicExt.Add "docx",strBaseDir & "\Doc"
dicExt.Add "exe",strBaseDir & "\Exe"
dicExt.Add "zip",strBaseDir & "\Zip"
dicExt.Add "png",strBaseDir & "\Png"

'dicExt.Add "txt",strBaseDir & "\Txt"
' ==============================================================================
' M A I N   L O G I C
' ==============================================================================

' Process each file in the base folder
Set objBaseDir = objFSO.GetFolder(strBaseDir)
For Each objFile In objBaseDir.Files
    ProcessFile objFile
Next    

' ==============================================================================
' W R A P U P
' ==============================================================================

' Done, cleanup and exit
'objFile.Close
objLogFile.Close
Wscript.Quit

' ==============================================================================
' S U B R O U T I N E S   &   F U N C T I O N S
' ==============================================================================


Sub ProcessFile(objFile)
    ' Process a file, first get extension
    strExt = objFSO.GetExtensionName(objFile.Path)

    ' If exists in defined extensions with destination folders use that folder, else use default
    If dicExt.Exists(strExt) Then
        strMoveToDir = dicExt.Item(strExt)
    End If

    ' Create the destination folder if needed
    If Not objFSO.FolderExists(strMoveToDir) Then
        objLogFile.WriteLine Now() & " *WARNING* Creating destination directory """ & strMoveToDir & """"
        MakeDir strMoveToDir
    End If

    ' Move the file
    objLogFile.WriteLine Now() & " *INFO* Moving file """ & objFile.Name & """ to directory """ & strMoveToDir & """"
    objFile.Move strMoveToDir & "\" & objFile.Name
End Sub

Sub MakeDir(ByVal strPath)
  On Error Resume Next

  Err.Clear
  If Not FolderExists(strPath) Then
    ParentFolder = FolderGetParentName(strPath)
    If Len(ParentFolder) > 0 Then
      MakeDir ParentFolder
      FolderCreate strPath
    End If
  End If
End Sub

Sub FolderCreate(AFolder)
  On Error Resume Next

  Err.Clear
  objFSO.CreateFolder AFolder
  If Err.Number > 0 Then
    WScript.Echo "FolderCreate('" & AFolder & "'): " & Err.Description
    Err.Clear
  End If
End Sub

Function FolderExists(AFolder)
  On Error Resume Next

  Err.Clear
  FolderExists = objFSO.FolderExists(AFolder)
  If Err.Number > 0 Then
    WScript.Echo "FolderExists('" & AFolder & "'): " & Err.Description
    Err.Clear
  End If
End Function

Function FolderGetParentName(AFolder)
  On Error Resume Next

  Err.Clear
  FolderGetParentName = objFSO.GetParentFolderName(AFolder)
  If Err.Number > 0 Then
    WScript.Echo "FolderGetParentName('" & AFolder & "'): " & Err.Description
    Err.Clear
  End If
End Function

Open in new window

Thank you.
Bill PrewIT / Software Engineering ConsultantCommented:
In your original question / problem (not the new code), before the error, what was displayed to the console?


»bp
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Bill PrewIT / Software Engineering ConsultantCommented:
Also, I think this is modified code from a solution I originally proposed at Batch & VBscript: move files based on extension

If so, then I notice that the default directory has been removed, which seems like it could be a problem when a matching extension is not found in the dictionary.  Not this code (below) that is no longer in place.  But before proposing changes I'd like to better understand the context of the error, what file was it processing, where in the code the error occurred, etc.

strDefaultDir = "B:\EE\EE29104964\Other"
.
.
.
    ' If exists in defined extensions with destination folders use that folder, else use default
    If dicExt.Exists(strExt) Then
        strMoveToDir = dicExt.Item(strExt)
    Else
        strMoveToDir = strDefaultDir
    End If

Open in new window


»bp
LD16Author Commented:
Hello Bill,
True, I remove strDefaultDir as the new need is just to move the files reported in the script. If I kept strDefaultDir I got a move of not reported files such as log file which is causing me the accessdenied.
The new need is just to move files reported in the dict.
Thank you!
LD16Author Commented:
Hello Bill,
Let me know if you need additional information.
Thank you very much for your help.
Bill PrewIT / Software Engineering ConsultantCommented:
Made a couple of small changes, see if these help.

' ==============================================================================
' C O N S T A N T S   &   V A R I A B L E S
' ==============================================================================

' Define needed constants
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const TriStateUseDefault = -2

' Specify path to folder of files to process, default destination, and log file
strScriptDir = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
strBaseDir = strScriptDir
strLogFile = strScriptDir & "log-file.log"

' ==============================================================================
' I N I T I A L I Z A T I O N
' ==============================================================================

' Create filesystem object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Open log file (append)
Set objLogFile = objFSO.OpenTextFile(strLogFile, ForWriting, True)

' Make sure base directory exists
If Not objFSO.FolderExists(strBaseDir) Then
    objLogFile.WriteLine Now() & " *ERROR* Base directory does not exist """ & strBaseDir & """"
    Wscript.Quit()
End If

' Create a dictionary to hold the list of extensions to move, and destination folders
Set dicExt = CreateObject("Scripting.Dictionary")
dicExt.CompareMode = vbTextCompare

' Add the extensions to the dictionary, and the destination folders
dicExt.Add "pdf",strBaseDir & "Pdf"
dicExt.Add "xls", strBaseDir & "Xl"
dicExt.Add "xlsx",strBaseDir & "Xl"
dicExt.Add "xlsm",strBaseDir & "Xl"
dicExt.Add "txt",strBaseDir & "Txt"
dicExt.Add "pptx",strBaseDir & "Ppt"
dicExt.Add "doc",strBaseDir & "Doc"
dicExt.Add "docx",strBaseDir & "Doc"
dicExt.Add "exe",strBaseDir & "Exe"
dicExt.Add "zip",strBaseDir & "Zip"
dicExt.Add "png",strBaseDir & "Png"

'dicExt.Add "txt",strBaseDir & "Txt"
' ==============================================================================
' M A I N   L O G I C
' ==============================================================================

' Process each file in the base folder
Set objBaseDir = objFSO.GetFolder(strBaseDir)
For Each objFile In objBaseDir.Files
    ProcessFile objFile
Next    

' ==============================================================================
' W R A P U P
' ==============================================================================

' Done, cleanup and exit
objFile.Close
objLogFile.Close
Wscript.Quit

' ==============================================================================
' S U B R O U T I N E S   &   F U N C T I O N S
' ==============================================================================


Sub ProcessFile(objFile)
    ' Process a file, first get extension
    strExt = objFSO.GetExtensionName(objFile.Path)

    ' If exists in defined extensions with destination folders use that folder, else use default
    If dicExt.Exists(strExt) Then
        strMoveToDir = dicExt.Item(strExt)

        ' Create the destination folder if needed
        If Not objFSO.FolderExists(strMoveToDir) Then
            objLogFile.WriteLine Now() & " *WARNING* Creating destination directory """ & strMoveToDir & """"
            MakeDir strMoveToDir
        End If

        ' Move the file
        objLogFile.WriteLine Now() & " *INFO* Moving file """ & objFile.Name & """ to directory """ & strMoveToDir & """"
        objFile.Move strMoveToDir & "\" & objFile.Name
    End If
End Sub

Sub MakeDir(ByVal strPath)
    ' Small recursive function to create a folder (and all parent folders in path if needed)
    If Not objFSO.FolderExists(strPath) Then
        ' Make sure parent of this folder exists first
        If objFSO.GetParentFolderName(strPath) <> "" Then
            MakeDir objFSO.GetParentFolderName(strPath)
        End If
        ' Now create this folder
        objFSO.CreateFolder strPath
    End If
End Sub

Open in new window


»bp
LD16Author Commented:
Thank you very much Bill it works. I got an error message concerning line 65 however I commented it, I don't know if we need this line as the file is just moved.
I also noticed that when file exists an error message is displayed. Possible to omit move and, display a msgbox "Unable to proceed as file: File name exists" and quit the procedure?
Thank you very much for your help.
Bill PrewIT / Software Engineering ConsultantCommented:
Okay, try this.

' ==============================================================================
' C O N S T A N T S   &   V A R I A B L E S
' ==============================================================================

' Define needed constants
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const TriStateUseDefault = -2

' Specify path to folder of files to process, default destination, and log file
strScriptDir = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
strBaseDir = strScriptDir
strLogFile = strScriptDir & "log-file.log"

' ==============================================================================
' I N I T I A L I Z A T I O N
' ==============================================================================

' Create filesystem object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Open log file (append)
Set objLogFile = objFSO.OpenTextFile(strLogFile, ForWriting, True)

' Make sure base directory exists
If Not objFSO.FolderExists(strBaseDir) Then
    objLogFile.WriteLine Now() & " *ERROR* Base directory does not exist """ & strBaseDir & """"
    Wscript.Quit()
End If

' Create a dictionary to hold the list of extensions to move, and destination folders
Set dicExt = CreateObject("Scripting.Dictionary")
dicExt.CompareMode = vbTextCompare

' Add the extensions to the dictionary, and the destination folders
dicExt.Add "pdf",strBaseDir & "Pdf"
dicExt.Add "xls", strBaseDir & "Xl"
dicExt.Add "xlsx",strBaseDir & "Xl"
dicExt.Add "xlsm",strBaseDir & "Xl"
dicExt.Add "txt",strBaseDir & "Txt"
dicExt.Add "pptx",strBaseDir & "Ppt"
dicExt.Add "doc",strBaseDir & "Doc"
dicExt.Add "docx",strBaseDir & "Doc"
dicExt.Add "exe",strBaseDir & "Exe"
dicExt.Add "zip",strBaseDir & "Zip"
dicExt.Add "png",strBaseDir & "Png"

'dicExt.Add "txt",strBaseDir & "Txt"
' ==============================================================================
' M A I N   L O G I C
' ==============================================================================

' Process each file in the base folder
Set objBaseDir = objFSO.GetFolder(strBaseDir)
For Each objFile In objBaseDir.Files
    ProcessFile objFile
Next    

' ==============================================================================
' W R A P U P
' ==============================================================================

' Done, cleanup and exit
objLogFile.Close
Wscript.Quit

' ==============================================================================
' S U B R O U T I N E S   &   F U N C T I O N S
' ==============================================================================


Sub ProcessFile(objFile)
    ' Process a file, first get extension
    strExt = objFSO.GetExtensionName(objFile.Path)

    ' If exists in defined extensions with destination folders use that folder, else use default
    If dicExt.Exists(strExt) Then
        strMoveToDir = dicExt.Item(strExt)

        ' Create the destination folder if needed
        If Not objFSO.FolderExists(strMoveToDir) Then
            objLogFile.WriteLine Now() & " *WARNING* Creating destination directory """ & strMoveToDir & """"
            MakeDir strMoveToDir
        End If

        ' Move the file (if it doesn't already exist)
        If Not objFSO.FileExists(strMoveToDir & "\" & objFile.Name) Then
            objLogFile.WriteLine Now() & " *INFO* Moving file """ & objFile.Name & """ to directory """ & strMoveToDir & """"
            objFile.Move strMoveToDir & "\" & objFile.Name
        Else
            MsgBox "Unable to proceed as file already exists: " & strMoveToDir & "\" & objFile.Name
            Exit Sub
        End If
    End If
End Sub

Sub MakeDir(ByVal strPath)
    ' Small recursive function to create a folder (and all parent folders in path if needed)
    If Not objFSO.FolderExists(strPath) Then
        ' Make sure parent of this folder exists first
        If objFSO.GetParentFolderName(strPath) <> "" Then
            MakeDir objFSO.GetParentFolderName(strPath)
        End If
        ' Now create this folder
        objFSO.CreateFolder strPath
    End If
End Sub

Open in new window


»bp

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
LD16Author Commented:
Tested and it works!
Thank you very much for your help Bill!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
VB Script

From novice to tech pro — start learning today.