Search code examples
listapplescriptdirectorysubdirectory

Get full directory contents with AppleScript


I need to get the entire (visible) contents of a folder and its subfolders as a list. Is this possible?


Solution

  • I'm sure there is a shell command that can do this faster, but here is one way in pure Applescript that gives you total control over formatting what info you would like displayed.

    property kFileList : {}
    
    tell application "Finder"
        set source_folder to choose folder with prompt "Please select directory."
        my createList(source_folder)
    end tell
    
    on createList(item_list)
        set the the_items to list folder item_list without invisibles
        set item_list to item_list as string
        repeat with i from 1 to number of items in the the_items
            set the_item to item i of the the_items
            set the_item to (item_list & the_item) as alias
            set this_info to info for the_item
            set file_name to name of this_info
            set end of kFileList to file_name
            if folder of this_info is true then
                my createList(the_item)
            end if
        end repeat
    end createList
    

    On a side note, there are also a number file listing applications that can do this faster than Applescript.

    UPDATE: As a result of this discussion, here is the function again, but this time using the updated API. This could probably could use some cleaning up, but it works cataloging my Desktop handily enough (and that's a deep, deep folder for me):

    property kFileList : {}
    
    tell application "Finder"
        set source_folder to choose folder with prompt "Please select directory."
        my createList(source_folder)
    end tell
    
    return kFileList
    
    on createList(mSource_folder)
        set item_list to ""
        
        tell application "System Events"
            set item_list to get the name of every disk item of mSource_folder
        end tell
        
        set item_count to (get count of items in item_list)
        
        repeat with i from 1 to item_count
            set the_properties to ""
            
            set the_item to item i of the item_list
            set the_item to ((mSource_folder & the_item) as string) as alias
            
            tell application "System Events"
                set file_info to get info for the_item
            end tell
            
            if visible of file_info is true then
                set file_name to displayed name of file_info
                set end of kFileList to file_name
                if folder of file_info is true then
                    my createList(the_item)
                end if
            end if
            
        end repeat
    end createList