Search code examples
applescriptparent-child

AppleScript - How to get a folder's first child path (only when the first child is a folder, not a file)?


How do you get a folder's first child path (when the first child is a folder)?

Say you have...

Folder 1 ¬
  File 1
  File 2
  Folder 2 ¬
    File A
    File B
    File C
    File D

Use case:

I select a batch of folders, all on the same level as Folder 1 with: set foldersToProcess to choose folder with multiple selections allowed

Then, I loop through each each of the queued folder foldersToProcess, where in the process I want to look into the first child folder of Folder 1 (being Folder 2), every single time.

How do I do this?


Solution

  • You should use try block because maybe some of the chosen folders doesn't contain subfolders at all. So, without try block it will throw error when asking for folder 1 of empty list.

    To get first folders as System Event's folder references:

    set chosenFolders to (choose folder with multiple selections allowed)
    
    set firstFolders to {}
    repeat with anAlias in chosenFolders
        try
            tell application "System Events" to ¬
                set end of firstFolders to folder 1 of folder (anAlias as text)
        end try
    end repeat
    

    To get HFS paths of first folders, edit corresponding code line with:

    tell application "System Events" to ¬
                set end of firstFolders to path of folder 1 of folder (anAlias as text)
    

    To get Posix paths of first folders,edit corresponding code line with:

    tell application "System Events" to ¬
                set end of firstFolders to POSIX path of folder 1 of folder (anAlias as text)