himorogiの日記

主にプログラミングに関することなど。少々ハード(電子工作)についても。

macOS で Powershell - using osascript 編

Windows 版の Powershell では System.Windows.Forms から Userform を簡単に作れるけど、macOS + Powershell.netcore でもせめて Dialog くらい出したいので検討したが、一番簡単で手っ取り早いのは osascript つまり AppleScript から display dialog などを使う方法ではないだろうか。

PS /Users/hoge> 'display dialog "Hello World"' | osascript
button returned:OK
PS /Users/hoge>

display dialog の戻り値は基本的に button returned:(button 名) だけど、cancel したときは以下のように。

PS /Users/hoge> 'display dialog "Hello World"' | osascript                       
0:28: execution error: ユーザによってキャンセルされました。 (-128)
PS /Users/hoge>

なお、title や icon を指定することもできる。icon は 'note'、'caution'、'stop' の三種類が指定できる。

PS /Users/hoge> 'display dialog "Hello World" with title "dialog window"' | osascript
button returned:OK
PS /Users/hoge> display dialog "Note" with title "Using ICON" with icon note' | osascript
button returned:OK
PS /Users/hoge>

また、button は任意のもの(リスト)を設定することもできる。

PS /Users/hoge> 'display dialog "What’s color?" buttons("R","G","B")' | osascript
button returned:G
PS /Users/hoge>

複数 button 選択するには choose も使える。

PS /Users/hoge> 'choose from list {"R","G","B"} default items "R" with title "color select"' | osascript
B
PS /Users/hoge>

display dialog とよく似たものに display alert もあるけど、使い方はほぼ同じなのと、display daialog でだけで間に合うので省略。
試してみたいときは AppleScript の情報をたどって欲しい。

また、通知センターに notification を表示する、という方法もある。

PS /Users/hoge> 'display notification "hello"' | osascript   
PS /Users/hoge>

これだけでは物足りないので、JXA(Javascript Automation:Javascript で記述する osascript)でも書いてみた。

PS /Users/hoge> @"
>> var Notice = Application.currentApplication()
>> Notice.includeStandardAdditions = true
>> Notice.displayNotification('hello world' )
>> "@ | osascript -l JavaScript
PS /Users/hoge>