More Complex Powershell AppleScript interactions

What If You Need More Than One Line?

So in the process of creating my series of ways to have PowerShell connect to AppleScript, thereby giving PowerShell far more access to the richness of what macOS has to offer, I realized that what I’d been doing had been limited to one-line commands. Choose File, Display Dialog, etc. Those are valuable, but sometimes, you need more than one line.

Now, usually, you’ll see a lot of really weird calls to osascript -e with complex quoting and escaping, things that tend to not work terribly well within the PowerShell world on macOS. But, there is another way to use the AppleScript runtime from the shell environment. You create a shell script, i.e. “osatest.sh”, but for the shebang, you use #!/usr/bin/osascript instead of the usual #!/bin/bash.

The advantage of this method is that you can then write fairly complex scripts with multiple lines, user input, probably even application control, and then provide a return to the powershell environment in a number of ways, i.e. return values or a return file path.

As a short example, here’s one I used in testing:

#!/usr/bin/osascript

display dialog "Look ma, multiple steps with osascript and no funky quotes!"
display alert "THIS IS SO COOL"
beep
set theList to {firstword:"This",secondword:"Is",thirdword:"a",fourthword:"list"}
return theList

So this does a few simple things. Displays a dialog, displays an alert, builds a record, assigns it to a variable, and returns the variable to the calling process. But it’s literally bog-standard AppleScript. No special escaping or quoting needed, multiple lines are fine. you could copy everything but the shebang line into the macOS script editor, and it would work fine. (I literally did that, it did in fact work correctly)

If you call it from PowerShell, it works as expected, nothing funky:

/Users/homedir/osatest.sh

firstword:This, secondword:Is, thirdword:a, fourthword:list

So you can return basic data types, numbers, strings, records, lists to PowerShell from AppleScript and then use that within PowerShell. Which creates some complex potential for more than just one-off commands.

You can even have some back and forth, wherein you use the one-off commands to get information from the user to build a proper .sh script that is run against the AppleScript runtime, do things in other apps, like the Finder, Word, Photoshop, <other scriptable thing>, and then return usable results to PowerShell.

I’m a bit busy for the next month or so, but I’ll try to get some examples going to show just how neat this can be. I’m also going to start using the tag “powershell-applescript-bridge” to help folks find these posts easier.