Search code examples
macosrecursionapplescript

AppleScript Processing Files in Folders recursively


I have a root folder and there are sub folders in it. It is generally one level only but it can be deeper. These folders will have different files including some .rar files. I want to create a recursive function which traverses the folders, check if the file is a rar file and open/extract it. The code is working to first level with out any problem. But the recursive call is not working and apple script's error handling is horrible. Here is the code which I have done so far.

set folderName to "Macintosh HD:Users:Teja:Desktop:Madhu Babu:"

process_folder("", folderName)

on process_folder(root, folderNameToProcess)
    set fileExt to {".rar"}
    tell application "Finder"
        set theItems to every file of folder (root & folderNameToProcess)
        repeat with theFile in theItems
            copy name of theFile as string to FileName
            repeat with ext in fileExt
                if FileName ends with ext then
                    open theFile
                    delete theFile
                end if
            end repeat
        end repeat
        set theFolders to name of folders of folder (root & folderNameToProcess)
        repeat with theFolder in theFolders
            copy theFolder as string to TheFolderName
            display dialog (folderNameToProcess & TheFolderName & ":")
            try
                process_folder(folderNameToProcess, TheFolderName & ":")
            on error errStr number errorNumber
                display dialog errStr
            end try
        end repeat
    end tell
end process_folder

Solution

  • Try changing your recursive call to

    try
        my process_folder(folderNameToProcess, TheFolderName & ":")
    on error errStr number errorNumber
        display dialog errStr
    end try
    

    Note the my before the process_folder call. This made it work for me.