I'm looking to write a script which outputs a list of all the window titles of all the currently running programs. Is there any way to do this with AppleScript? I tried running the following code:
tell application "System Events"
repeat with theProcess in (every process)
if background only of theProcess is false then
say (name of theProcess) as string
end if
end repeat
end tell
I put it in a file called lawl.scpt
and then ran the following in the Terminal:
$ osascirpt lawl.scpt
However, it just pauses for a few seconds, then exits without outputting anything.
Best Answer
The easy, one-liner method of achieving this in AppleScript is:
Annoyingly, this returns a nested lists, which you'll either have to loop through in a
repeat with
block, or flatten the nest into a simple list (which isn't too hard).Running AppleScript from the command line has the advantage that the returned data are in text format, which can be manipulated quite easily. You can even make use of the command line from within AppleScript to get the benefits of each:
which returns a nice, straight forward, text list of window titles.
Finally, here's a formal AppleScript to get the job done properly, in a way that allows you to retain the ability to reference the window object if you need to get other properties or manipuoate it:
The resulting list is a list of records that have the structure of
property R
. Each record represents a single window, which contains the window's title and the name of the process it belongs to, e.g.{WindowTitle:"Downloads", AttachedToProcess:"Finder"}
. This way, it's easy to do things with the window, such as: