Link to home
Start Free TrialLog in
Avatar of Luis Diaz
Luis DiazFlag for Colombia

asked on

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.
Avatar of ste5an
ste5an
Flag of Germany image

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

Avatar of Luis Diaz

ASKER

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.
Avatar of Bill Prew
Bill Prew

In your original question / problem (not the new code), before the error, what was displayed to the console?


»bp
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
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!
Hello Bill,
Let me know if you need additional information.
Thank you very much for your help.
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
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.
ASKER CERTIFIED SOLUTION
Avatar of Bill Prew
Bill Prew

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Tested and it works!
Thank you very much for your help Bill!