Any way to get the “Open With…” list via AppleScript

applescriptfinder

I want to create an AppleScript that gets the Finder selection and displays a list of applications that are capable of opening it.

In other words, is there any way to get the list of apps that appears when you use Finder's "Open With >" contextual submenu?

Best Answer

One option would be to use AllApplications in a shell script:

tell application "Finder"
    set p to POSIX path of (item 1 of (get selection) as text)
end tell
set l to do shell script "~/bin/AllApplications -path " & quoted form of p & " | sed 's/.*\\///g;s/\\.app$//g' | sort -f | uniq"
set answer to choose from list (paragraphs of l) without multiple selections allowed
if answer is false then return
set a to item 1 of answer
set p to path to application a
tell application "Finder" to open selection using p

You could also use System Events to get the applications from the Open With menu:

tell application "System Events" to tell process "Finder"
    set l to name of menu items of menu 1 of menu item "Open With" of menu 3 of menu bar 1
end tell
set text item delimiters to linefeed
set l2 to do shell script "grep -vx 'missing value' <<< " & quoted form of (l as text) & " | grep -vx Other… | sed -E 's/ \\([^)]*\\)$//g;s/ \\(default\\)$//g;s/\\.app$//g' | sort -f | uniq"
set answer to choose from list (paragraphs of l2) without multiple selections allowed
if answer is false then return
set a to item 1 of answer
set p to (path to application a)
tell application "Finder" to open selection using p

I didn't really test the scripts, but they're probably affected by rdar://9406282: Finder scripting selection may refer to bogus value not correlated with UI.

Related questions at Super User: