Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

カテゴリー: System

今日のYYYY,MM,DDを取得する

Posted on 2月 13, 2018 by Takaaki Naganoya
AppleScript名:今日のYYYY,MM,DDを取得する
— Created 2015-12-26 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set aCalend to current application’s NSCalendar’s currentCalendar()
set aDate to current application’s NSDate’s |date|()

set aYear to aCalend’s component:(current application’s NSCalendarUnitYear) fromDate:aDate
set aYearStr to numToZeroPaddingStr(aYear, 4, "0") of me

set aMonth to aCalend’s component:(current application’s NSCalendarUnitMonth) fromDate:aDate
set aMonthStr to numToZeroPaddingStr(aMonth, 2, "0") of me

set aDay to aCalend’s component:(current application’s NSCalendarUnitDay) fromDate:aDate
set aDayStr to numToZeroPaddingStr(aDay, 2, "0") of me

set dStr to aYearStr & aMonthStr & aDayStr
–> "20171219"

–整数の値に指定桁数ゼロパディングして文字列で返す
on numToZeroPaddingStr(aNum as integer, aDigit as integer, paddingChar as text)
  set aNumForm to current application’s NSNumberFormatter’s alloc()’s init()
  
aNumForm’s setPaddingPosition:(current application’s NSNumberFormatterPadBeforePrefix)
  
aNumForm’s setPaddingCharacter:paddingChar
  
aNumForm’s setMinimumIntegerDigits:aDigit
  
  
set bNum to current application’s NSNumber’s numberWithInt:aNum
  
set aStr to aNumForm’s stringFromNumber:bNum
  
  
return aStr as text
end numToZeroPaddingStr

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

epoch timeをdateに変換

Posted on 2月 13, 2018 by Takaaki Naganoya
AppleScript名:epoch timeをdateに変換
— Created 2017-12-19 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set epochTimeStr to current application’s NSString’s stringWithString:"1401325412"
set aDate to (current application’s NSDate’s alloc()’s initWithTimeIntervalSince1970:(epochTimeStr’s doubleValue())) as date
–>  (NSDate) 2014-05-29 01:03:32 +0000
–>  date "2014年5月29日木曜日 10:03:32"

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

現在時刻のepoch timeを取得する

Posted on 2月 13, 2018 by Takaaki Naganoya
AppleScript名:現在時刻のepoch timeを取得する
— Created 2017-12-19 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set curDate to current application’s NSDate’s |date|()
set epochSeconds to (curDate’s timeIntervalSince1970())

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

iBooksライブラリ中のepubファイルから情報を取得 v3

Posted on 2月 13, 2018 by Takaaki Naganoya
AppleScript名:iBooksライブラリ中のepubファイルから情報を取得 v3
— Created 2017/02/26 by Christopher Stone
— Modified 2017/11/01 by Takaaki Naganoya
use framework "Foundation"
use scripting additions
use mdLib : script "Metadata Lib" version "1.0.0" –https://www.macosxautomation.com/applescript/apps/Script_Libs.html#Metadata_Lib

property NSString : a reference to current application’s NSString
property NSMutableArray : a reference to current application’s NSMutableArray
property NSPropertyListFormat : a reference to current application’s NSPropertyListFormat
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSPropertyListImmutable : a reference to current application’s NSPropertyListImmutable
property NSPropertyListSerialization : a reference to current application’s NSPropertyListSerialization

set aPath to POSIX path of (path to library folder from user domain)
set sourceFolder to aPath & "Containers/com.apple.BKAgentService/Data/Documents/iBooks/Books/"

set textFiles to mdLib’s searchFolders:{sourceFolder} searchString:"kMDItemContentType contains %@ || kMDItemContentType contains %@ " searchArgs:{"com.apple.ibooks-folder", "org.idpf.epub-container"}

set outDicList to NSMutableArray’s new()
repeat with i in textFiles
  set aFile to (i as string)
  
  
if aFile ends with "/" then
    set aFullPath to aFile & "iTunesMetadata.plist"
  else
    set aFullPath to aFile & "/iTunesMetadata.plist"
  end if
  
  
try
    set xmlData to read ((POSIX file aFullPath) as alias) as «class utf8»
    
set xRes to readPlistFromStr(xmlData) of me
    
log xRes as list of string or string –as anything (maybe record or missing value)
    
    
(*cover-writing-mode:vertical, genre:教育, scroll-axis:default, sort-artist:あっぷる, BKITunesMigratedMetadata:PersistentID:6.68315366592803E+18, seriesTitle:Everyone Can Code, sort-name:Swiftによるあぷりけーしょん開発:入門編, itemId:1209648719, apple-id:xxxxxxxxxxxx@xxx.xxx, fileExtension:ibooks, year:2017, releaseDate:2017-03-19T07:00:00Z, BKInsertionDate:512115887, asset-info:flavor:pluspub, file-size:60642970, book-info:publication-version:162901775, PageProgression:default, asset-info:flavor:pluspub, file-size:60642970, package-file-hash:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX, BKAllocatedSize:82993152, longDescription:このコースでは、Swiftという言語を使って基本的なプログラミングの土台をしっかりと作り上げていきます。基本的なiOSアプリケーションを一から開発するために必要なツール、手法、概念を活用して、実践的な練習に取り組みます。さらに、プログラミングと優れたアプリケーション開発の土台となる、ユーザーインターフェイス設計の基本原則についても学習します。このコースを受講するにあたってプログラミングの経験は必要ありません。プログラミングの経験がある場合、レッスンの最初の方は簡単に読み進めていただくとよいでしょう。このブックではプログラミングの基礎にとどまらず、ソフトウェア開発ツールや概念、ベストプラクティスについても学習できます。, artistId:9.39801385E+8, artistName:Apple Education, isPreview:false, BKDisplayName:mzbf.eqmpijqw..d2.dlv.d2.dlv.ibooks, human-friendly-publication-version:1.1, shouldDisableTouchEmulation:true, vendorId:379015, drmVersionNumber:0, kind:ebook, s:143462, genreId:10037, explicit:2, seriesAdamId:1.118575554E+9, publisher:Apple Inc. – Education, versionRestrictions:16843008, BKGenerationCount:2, desktopSupportLevel:supported, primaryLanguage:ja, itemName:Swiftによるアプリケーション開発:入門編, purchaseDate:2017-03-25T06:21:26Z, shouldDisableOptimizeSpeed:true, obeyPageBreaks:1, pageCount:244*)
    
if xRes is not equal to missing value then
      (outDicList’s addObject:xRes)
    end if
  end try
end repeat

return outDicList as list of string or string –as anything

–stringのplistを読み込んでNSDictionaryに
on readPlistFromStr(theString)
  set aSource to NSString’s stringWithString:theString
  
set pListData to aSource’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aPlist to NSPropertyListSerialization’s propertyListFromData:pListData mutabilityOption:(NSPropertyListImmutable) |format|:(NSPropertyListFormat) errorDescription:(missing value)
  
return aPlist
end readPlistFromStr

★Click Here to Open This Script 

Posted in file System | Tagged 10.11savvy 10.12savvy 10.13savvy iBooks | Leave a comment

文字列で与えたシェルコマンドを実行する v2

Posted on 2月 13, 2018 by Takaaki Naganoya

do shell scriptコマンドとほぼ等価な、Cocoaの機能を用いたshell script実行のAppleScriptです。

よく「Terminal.app上のshell scriptをそのままdo shell scriptコマンドで実行して動かない」という声を聞きますが、そもそも環境変数が全然違うのでそのまま動くはずがありません。

AppleScriptのdo shell scriptコマンドは、いまのmacOSのセキュリティ向上の流れで行けば確実に近い将来に「デフォルトで実行禁止」「環境設定でオンにしてはじめて実行可能に」という扱いになることでしょう。

Cocoaのshell command呼び出し機能についても同様の制限が加わるかどうかは不明ですが、Cocoa経由でのshell command呼び出しAppleScriptについて調べておきました。

AppleScript名:文字列で与えたシェルコマンドを実行する v2
— Created 2016-02-13 by Takaaki Naganoya
— 2016 Piyomaru Software
–以下を参照:
–http://stackoverflow.com/questions/412562/execute-a-terminal-command-from-a-cocoa-app
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aRes to (runCommandString("pwd") of me) as string
–>  "/"

set bRes to (runCommandString("cd & ls -la") of me) as string

–Lock Screen
–runCommandAtPath("/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession", "-suspend") of me

–文字列で与えたシェルコマンドを実行する
on runCommandString(commandStr as string)
  set aPipe to current application’s NSPipe’s pipe()
  
set aTask to current application’s NSTask’s alloc()’s init()
  
aTask’s setLaunchPath:"/bin/sh"
  
aTask’s setArguments:{"-c", current application’s NSString’s stringWithFormat_("%@", commandStr)} –stringWithFormatはASOCに書き換え時の要注意点
  
aTask’s setStandardOutput:aPipe
  
set aFile to aPipe’s fileHandleForReading()
  
aTask’s |launch|()
  
return current application’s NSString’s alloc()’s initWithData:(aFile’s readDataToEndOfFile()) encoding:(current application’s NSUTF8StringEncoding)
end runCommandString

–指定したパスのシェルコマンドを実行する(結果などは取得しない)
on runCommandAtPath(commandPath as string, anArgument as string)
  set aTask to current application’s NSTask’s alloc()’s init()
  
aTask’s setLaunchPath:commandPath
  
aTask’s setArguments:(current application’s NSArray’s arrayWithObject:anArgument)
  
aTask’s |launch|()
end runCommandAtPath

★Click Here to Open This Script 

Posted in shell script System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ドメイン名からIPアドレスを取得

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:ドメイン名からIPアドレスを取得
— Created 2016-04-03 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set anIP to ((current application’s NSHost’s hostWithName:"www.google.com")’s address()) as string
–>  "216.58.200.196"

★Click Here to Open This Script 

Posted in Network System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

インターネット接続確認

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:インターネット接続確認
— Created 2015-12-16 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aRes to hasInternetConnection() of me
–>  true

on hasInternetConnection()
  set aURL to current application’s |NSURL|’s alloc()’s initWithString:"http://www.google.com"
  
set aReq to current application’s NSURLRequest’s alloc()’s initWithURL:aURL cachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:5.0
  
set urlRes to (current application’s NSURLConnection’s sendSynchronousRequest:aReq returningResponse:(missing value) |error|:(missing value))
  
if urlRes = missing value then
    return false
  else
    return true
  end if
end hasInternetConnection

★Click Here to Open This Script 

Posted in Network System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Twitter投稿

Posted on 2月 11, 2018 by Takaaki Naganoya

macOS 10.13まではTwitter投稿やFacebook連携などもOSに組み込まれていたので、手軽にこうした機能を利用でき、macOS 10.13までの環境ではこのように呼び出せるようになっていました。

macOS 10.14から方針が変わり、これらの機能はOSに組み込まれなくなりました。いまだと、REST API経由で投稿を行うことになるでしょうか。

AppleScript名:Twitter投稿
— Created 2015-01-24 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set aString to "ぴよ〜"

set twService to current application’s NSSharingService’s sharingServiceNamed:(current application’s NSSharingServiceNamePostOnTwitter)
set twService’s delegate to me

set shareItems to current application’s NSMutableArray’s alloc()’s initWithObjects:aString
tell twService to performWithItems:shareItems

★Click Here to Open This Script 

Posted in Network System | Tagged 10.11savvy 10.12savvy 10.13savvy Twitter

AirDropでファイルを送信する

Posted on 2月 11, 2018 by Takaaki Naganoya

Sharing Utilitiesを用いてAirDrop経由のファイル送信を行うAppleScriptです。

さすがに、Sharing Utilitiesは仕様も古いので、最新の環境に合わせて書き換えた「AirSharingLib Script Library」を配布、そちらを用いて同様の機能を実現するAppleScriptも掲載しています。

AppleScript名:AirDropでファイルを送信する
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use shareLib : script "Sharing Utilities" –https://macosxautomation.com/mavericks/libraries/examples.html

set anItem to choose file with prompt "Select File to send via AirDrop"
set aaList to {anItem}
begin AirDrop with aaList

★Click Here to Open This Script 

Posted in AirDrop Network System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

LAN上のHDDをマウントする v2

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:LAN上のHDDをマウントする v2
–SMB経由でマウント
set userAccount to "maro" –ユーザー名(環境に応じて書き換え)
set userPass to "xxxxxx" –パスワード(環境に応じて書き換え)
set aMachine to "smb://MBA11._smb._tcp.local/Macintosh HD" –11インチMacBook Air (10.9.2)でSMBのみ有効にしてテスト
mountVolume(aMachine, userAccount, userPass) of me –通常実行

–AFP経由でマウント
set userAccount to "maro" –ユーザー名(環境に応じて書き換え)
set userPass to "xxxxxx" –パスワード(環境に応じて書き換え)
set aMachine to "afp://MBA13._afpovertcp._tcp.local/Macintosh SSD" –13インチMacBook Air (10.7.5)でAFPとSMBの両方を有効にしてテスト
mountVolumeAsync(aMachine, userAccount, userPass) of me –非同期実行

–指定のネットワーク上のディスクをマウントする
on mountVolume(aMachine, userAccount, userPass)
  
  
try
    with timeout of 100 seconds
      mount volume aMachine as user name userAccount with password userPass
    end timeout
  on error
    return false
  end try
  
  
return true
  
end mountVolume

–指定のネットワーク上のディスクをマウントする(非同期実行)
on mountVolumeAsync(aMachine, userAccount, userPass)
  
  
try
    ignoring application responses
      mount volume aMachine as user name userAccount with password userPass
    end ignoring
  on error
    —
  end try
  
end mountVolumeAsync

★Click Here to Open This Script 

Posted in Network System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

無線LANデバイスのMACアドレスを取得する

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:無線LANデバイスのMACアドレスを取得する
— Created 2015-08-18 by Takaaki Naganoya
— Created 2015-08-18 by Shane Stanley
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "CoreWLAN"

set aRes to retWiFiMACaddress()
–>  "XX:XX:XX:XX:XX:XX"

–WiFi DeviceのMAC ADDRESSを返す
on retWiFiMACaddress()
  
  
–Get WLAN Device Name
  
set allNames to current application’s CWInterface’s interfaceNames()’s allObjects()
  
–>  (NSArray) {​​​​​"en0"​​​} –@MacBook Pro Retina 2012
  
  
set hitF to false
  
repeat with i from 1 to allNames’s |count|()
    set aInterface to (current application’s CWInterface’s interfaceWithName:(allNames’s objectAtIndex:(i – 1)))
    
if aInterface’s serviceActive() as boolean then
      set hitF to true
      
exit repeat
    end if
  end repeat
  
if hitF = false then return false –There is No WiFi Device (Broken or illigal configuration or Hackintosh)
  
  
set aHWAddress to aInterface’s hardwareAddress() as text
  
–>  "b8:xx:xx:xx:xx:xx"–MAC Address
  
  
return aHWAddress
  
end retWiFiMACaddress

★Click Here to Open This Script 

Posted in Network System WiFi | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

無線LANの各種情報を取得する v2.2

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:無線LANの各種情報を取得する v2.2
— Created 2015-08-18 by Shane Stanley
— Modified 2015-08-18 by Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "CoreWLAN"

–Get WLAN Device Name
set allNames to current application’s CWInterface’s interfaceNames()’s allObjects()
log allNames as list of string or string
–>  (NSArray) {​​​​​"en0"​​​} –@MacBook Pro Retina 2012

set hitF to false
repeat with i from 1 to allNames’s |count|()
  set aInterface to (current application’s CWInterface’s interfaceWithName:(allNames’s objectAtIndex:(i – 1)))
  
if aInterface’s serviceActive() as boolean then
    set hitF to true
    
exit repeat
  end if
end repeat
if hitF = false then return false –There is No WiFi Device

–WiFi device is Power On ?
repeat 10 times
  
  
set aPower to (aInterface’s powerOn()) as boolean
  
  
if aPower = false then
    –ActiveなWLANがない場合(WiFiをオフにしている)にはWiFiパワーオン
    
set wRes to aInterface’s setPower:true |error|:(missing value)
    
delay 1
  else
    exit repeat
  end if
end repeat

if aPower = false then return false –I could not power on WiFi deveice

set aChan to aInterface’s wlanChannel()
–>  (CWChannel) <CWChannel: 0x60000040cdd0> [channelNumber=1(2GHz), channelWidth={20MHz}]

set chanNumber to aChan’s channelNumber()
log chanNumber
–> 52
set chanBand to aChan’s channelBand() — 0 = unknown, 1 = 2GHz, 2 = 5GHz
log chanBand
–> 2
set chanWidth to aChan’s channelWidth() — 0 = unknown, 1 = 20MHz, 2 = 40MHz
log chanWidth
–> 2
set aTransRate to aInterface’s transmitRate()
log aTransRate
–>  162.0

set aChannnels to aInterface’s supportedWLANChannels()
–>  (NSSet) {​​​​​(CWChannel) <CWChannel: 0x60800020fad0> [channelNumber=1(2GHz), channelWidth={20MHz}, active], ​​​​​(CWChannel) <CWChannel: 0x60800020fb90> [channelNumber=2(2GHz), channelWidth={20MHz}, active], ​​​​​……………​​​​​(CWChannel) <CWChannel: 0x608000208410> [channelNumber=64(5GHz), channelWidth={20MHz}, DFS], ​​​​​(CWChannel) <CWChannel: 0x60800020f9e0> [channelNumber=136(5GHz), channelWidth={20MHz}, DFS]​​​}

set aSSIDdata to aInterface’s ssidData()
–>  (NSData) <45787472 xxxxxxxx xxxxxxxx xxxx>

set aSSID to aInterface’s ssid() as text
–>  "Extreme net_5G"

set aActive to aInterface’s serviceActive()
–>  true

set aSecurity to aInterface’s security()
–>  4

set aRSSIval to aInterface’s rssiValue()
–>  -72

set aPower to aInterface’s powerOn()
–>  true

set aNoise to aInterface’s noiseMeasurement()
–>  -91

set aIFname to aInterface’s interfaceName() as text
–>  "en0"

set aMode to aInterface’s interfaceMode()
–>  1

set aHWAddress to aInterface’s hardwareAddress() as text
–>  "b8:xx:xx:xx:xx:xx"–MAC Address

set aCountry to aInterface’s countryCode() as text
–>  "JP"

set aConfig to aInterface’s configuration()
–>  (CWConfiguration) <CWConfiguration: 0x6100002348e0>

set aCacheRes to aInterface’s cachedScanResults()
–>  (NSSet) {​​​​​(CWNetwork) <CWNetwork: 0x618000402740> ……………… [channelNumber=11(2GHz), channelWidth={20MHz}], ibss=0]​​​}

set aBSSID to aInterface’s bssid() as text
–>  "10:XX:XX:XX:XX:XX"

set aPhyMode to aInterface’s activePHYMode()
–>  4

★Click Here to Open This Script 

Posted in Network System WiFi | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

WiFiデバイスのパワーをオンに

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:WiFiデバイスのパワーをオンに
— Created 2015-08-18 by Shane Stanley
— Modified 2015-08-18 by Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "CoreWLAN"

set wRes to powerOnEveryWiFiDevices() of me

on powerOnEveryWiFiDevices()
  set allNames to current application’s CWInterface’s interfaceNames()’s allObjects() as list
  
if allNames = {} then return false
  
  
set powerList to {}
  
repeat with i in allNames
    set j to contents of i
    
set aInterface to (current application’s CWInterface’s interfaceWithName:j)
    
set wRes to (aInterface’s setPower:true |error|:(missing value))
    
set aPower to (aInterface’s powerOn()) as boolean
    
if aPower = false then
      display notification "Error occured in enabling an Wifi deviece ( " & j & " )…."
    end if
    
set the end of powerList to aPower
  end repeat
  
  
return ({true} is in powerList) –return whether some WiFi interface is on
end powerOnEveryWiFiDevices

★Click Here to Open This Script 

Posted in Network System WiFi | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

LAN上のファイルサーバー(smb)のホスト名を取得する

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:LAN上のファイルサーバー(smb)のホスト名を取得する
— Created 2015-12-24 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property foundHosts : {}
property myHostName : ""

findHostsViaBonjour("_smb._tcp") of me –smb’s port:445
–> {"MBA13"}

on findHostsViaBonjour(aType)
  
  
set foundHosts to {}
  
set myHostName to (current application’s NSHost’s currentHost()’s localizedName()) as string
  
  
set aBrowser to current application’s NSNetServiceBrowser’s alloc()’s init()
  
aBrowser’s setDelegate:me
  
  
aBrowser’s searchForServicesOfType:aType inDomain:""
  
  
repeat 1000 times
    if foundHosts is not equal to {} then exit repeat
    
delay 0.01
  end repeat
  
  
aBrowser’s setDelegate:(missing value)
  
  
return foundHosts
  
end findHostsViaBonjour

on netServiceBrowser:aNetServiceBrowser didFindService:aNetService moreComing:aMoreComing
  set aDesc to aNetServiceBrowser’s |description|()
  
set bDesc to aNetService’s |description|()
  
set cDesc to (aNetService’s |name|()) as text
  
  
if cDesc is not in foundHosts and cDesc is not equal to myHostName then
    set the end of foundHosts to cDesc
  end if
end netServiceBrowser:didFindService:moreComing:

★Click Here to Open This Script 

Posted in Network System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

LAN上のファイルサーバー(afp)のホスト名を取得する

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:LAN上のファイルサーバー(afp)のホスト名を取得する
— Created 2015-12-24 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property foundHosts : {}
property myHostName : ""

findHostsViaBonjour("_afpovertcp._tcp") of me –AFP’s port:548
–> {"MBA13", "Mini_2", "MBA11"}

on findHostsViaBonjour(aType)
  
  
set foundHosts to {}
  
set myHostName to (current application’s NSHost’s currentHost()’s localizedName()) as string
  
  
set aBrowser to current application’s NSNetServiceBrowser’s alloc()’s init()
  
aBrowser’s setDelegate:me
  
  
aBrowser’s searchForServicesOfType:aType inDomain:""
  
  
repeat 1000 times
    if foundHosts is not equal to {} then exit repeat
    
delay 0.01
  end repeat
  
  
aBrowser’s setDelegate:(missing value)
  
  
return foundHosts
  
end findHostsViaBonjour

on netServiceBrowser:aNetServiceBrowser didFindService:aNetService moreComing:aMoreComing
  set aDesc to aNetServiceBrowser’s |description|()
  
set bDesc to aNetService’s |description|()
  
set cDesc to (aNetService’s |name|()) as text
  
  
if cDesc is not in foundHosts and cDesc is not equal to myHostName then
    set the end of foundHosts to cDesc
  end if
end netServiceBrowser:didFindService:moreComing:

★Click Here to Open This Script 

Posted in Network System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Notification

Posted on 2月 8, 2018 by Takaaki Naganoya

macOS 10.10より、標準のScripting環境(スクリプトエディタ)上でCocoa-bridgeが使えるようになったので、Cocoa系のevent(Notification)が使えるようになったことを利用したサンプルです。

AppleScriptは基本的に、アプリケーションの機能や設定値を呼び出すためのもので、ごく一部の限られたアプリケーション以外からは「アプリケーション側からAppleScript(の所定のハンドラ)を呼び出す」方向のイベント呼び出しは利用できませんでした。

しかし、Cocoaのnotificationが利用できるようになったことで、多彩なイベント受信が行えるようになりました。

iTunes(or Music.app)の再生曲変更のnotificationを受信してやたらとTwitterなどに流そうとする入門Scripterがいるのですが(どこかの伝統芸か何かなんだろうか?)、そこはそんなに楽しいとも思えないし、本来のパワーを発揮していないとは思うのですが、見かけたらそっと触れないようにしておくことにしています。

AppleScript名:Notification
— Created 2017-10-13 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSDistributedNotificationCenter : a reference to current application’s NSDistributedNotificationCenter

on run
  NSDistributedNotificationCenter’s defaultCenter()’s addObserver:me selector:"statusChanged:" |name|:"com.apple.iTunes.playerInfo" object:(missing value)
  
end run

on statusChanged:sender
  tell application id "com.apple.iTunes"
    try
      tell current track
        set anAlbum to album
        
set aName to name
        
set anArtist to album artist
        
set aRating to rating
      end tell
    on error
      return
    end try
  end tell
  
display notification aName
end statusChanged:

★Click Here to Open This Script 

Posted in Noification System | Tagged 10.11savvy 10.12savvy 10.13savvy iTunes Music | Leave a comment

指定Bundle IDのプロセス存在確認(ASOC)v3

Posted on 2月 8, 2018 by Takaaki Naganoya
AppleScript名:指定Bundle IDのプロセス存在確認(ASOC)v3
— Created 2015-02-08 by Takaaki Naganoya
— Created 2017-02-26 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set aRes to chkAppProcesByBundleID("com.apple.iWork.Keynote")
–> true

on chkAppProcesByBundleID(aBundleID as string)
  set procArray to current application’s NSWorkspace’s sharedWorkspace’s runningApplications()’s valueForKeyPath:"bundleIdentifier"
  
return (procArray’s containsObject:aBundleID) as boolean
end chkAppProcesByBundleID

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

バンドルIDで指定したプロセスを強制終了(NSRunningApplication)

Posted on 2月 8, 2018 by Takaaki Naganoya

バンドルIDで指定したプロセスを強制終了させるAppleScriptです。

Finderを終了させてみると、あえて意図して起動しないとFinderが終了したままの状態で戻って来ません。

AppleScript名:バンドルIDで指定したプロセスを強制終了(NSRunningApplication)
— Created 2017-09-17 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set pRes to forceQuitAProcessByBUndleID("com.apple.finder") of me

–指定プロセスの強制終了
on forceQuitAProcessByBUndleID(aBundleID)
  set appArray to current application’s NSRunningApplication’s runningApplicationsWithBundleIdentifier:aBundleID
  
if appArray’s |count|() > 0 then
    set appItem to appArray’s objectAtIndex:0
    
set aRes to (appItem’s terminate()) as boolean
    
return aRes
  else
    return false
  end if
end forceQuitAProcessByBUndleID

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

他のアプリケーションを隠す

Posted on 2月 8, 2018 by Takaaki Naganoya
AppleScript名:他のアプリケーションを隠す
— Created 2017-01-07 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

current application’s NSWorkspace’s sharedWorkspace()’s hideOtherApplications()

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定名称のアプリケーションプロセスが存在すればその正しい名前を返す

Posted on 2月 8, 2018 by Takaaki Naganoya
AppleScript名:指定名称のアプリケーションプロセスが存在すればその正しい名前を返す
— Created 2015-07-29 16:43:11 +0900 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aName to "メール"
set aRes to returnExactNameOfAnApp(aName) of me

on returnExactNameOfAnApp(aName)
  tell application "System Events"
    set ap1List to every process whose name is equal to aName
    
if ap1List = {} then
      set ap1List to every process whose displayed name is equal to aName
      
if ap1List = {} then return false
    end if
    
set anApp to contents of first item of ap1List
    
return name of anApp
  end tell
end returnExactNameOfAnApp

★Click Here to Open This Script 

Posted in System | Tagged 10.11savvy 10.12savvy 10.13savvy System Events | Leave a comment

Post navigation

  • Older posts
  • Newer posts

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 15, Sequoia
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AppleScriptによる並列処理
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • macOS 15でも変化したText to Speech環境
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • デフォルトインストールされたフォント名を取得するAppleScript
  • macOS 15 リモートApple Eventsにバグ?
  • 【続報】macOS 15.5で特定ファイル名パターンのfileをaliasにcastすると100%クラッシュするバグ
  • AppleScript入門① AppleScriptってなんだろう?
  • Script Debuggerの開発と販売が2025年に終了
  • macOS 14で変更になったOSバージョン取得APIの返り値
  • NSObjectのクラス名を取得 v2.1
  • 有害ではなくなっていたSpaces
  • macOS 15:スクリプトエディタのAppleScript用語辞書を確認できない
  • Xcode上のAppleScriptObjCのプログラムから、Xcodeのログ欄へのメッセージ出力を実行

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (194) 14.0savvy (147) 15.0savvy (135) CotEditor (66) Finder (51) iTunes (19) Keynote (119) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (76) Pages (55) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • date
  • dialog
  • diff
  • drive
  • Droplet
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • process
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2025年6月
  • 2025年5月
  • 2025年4月
  • 2025年3月
  • 2025年2月
  • 2025年1月
  • 2024年12月
  • 2024年11月
  • 2024年10月
  • 2024年9月
  • 2024年8月
  • 2024年7月
  • 2024年6月
  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2024年2月
  • 2024年1月
  • 2023年12月
  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC