Search code examples
applescriptfinder

list subfolders using applescript


This is my first applescript. I thought I'd do something simple like navigating to a folder using a path and listing the subfolders...Unfortunately, I can't figure it out :-)

Here is what I've tried so far:

The first try:

tell application "Finder"
    set the_folder to POSIX path of "Users:MyName:Doc"
    log the_folder
    set folder_list to every item of folder the_folder
    log folder_list 
end tell

This produces an error: "Finder got an error: Can't get folder "/Users/MyName/Doc".

Could someone please: 1. Explain to me what I'm doing wrong. 2. Provide an example that works.

Thanks in advance.

btw the folder does exist on my machine...


Solution

  • UPDATE: Oops! It appears that I have given you the wrong information so I will give you the correct information.

    The command POSIX path of requires a complete alias reference. By that I mean supplying the full file reference (i.e. <your_disk_name>:Users:<your_user_name>:somefolder:). Make sure that if you're referring to a folder that you end the reference with a colon (i.e. Macintosh HD:Users:). An improved version would look like this:

    tell application "Finder"
      set the_folder to (POSIX path of ("<your_disk_name>:Users:<your_user_name>:Doc:") as alias) as alias
      set folder_list to every item of the_folder
    end tell
    

    OPTIONAL

    To coerce a POSIX path (i.e. /Users/<your_user_name>/somefolder) back into an alias, two conversions are needed.

    Conversion 1: The first step is to convert the reference into a file reference. To do this, place the words as POSIX file after the reference, like so:

    "/Users/<your_user_name>/somefolder" as POSIX file
    

    This code procudes a file reference in this form: file "<your_disk_name>:Users:<your_user_name>:somefolder:"

    Conversion 2: Add a second coercion, as alias, to the end of the reference...

    "/Users/<your_user_name>/somefolder" as POSIX file as alias
    

    This code produces an actual alias reference: alias "<your_disk_name>:Users:<your_user_name>:somefolder:

    If you have any questions, just ask. :)