AppleScript Basic

ファイルの上書きチェックとファイル名変更


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application


set strFilePath to ("~/Library/LaunchAgents/com.dropbox.DropboxMacUpdate.agent.plist")
set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)


set ocidFilePath to doChkExists(ocidFilePathURL)
log ocidFilePath as text


####################################
#上書きチェック
# ocid file path = NSPathStore を返します
####################################
to doChkExists(argFilePath)
log (className() of argFilePath) as text
  if (class of argFilePath) is text then
log "テキストファイルパス"
    set ocidFilePathStr to refMe's NSString's stringWithString:(argFilePath)
    set ocidArgFilePath to ocidFilePathStr's stringByStandardizingPath()
  else if (class of argFilePath) is alias then
log "エリアスファイルパス"
    set strArgFilePath to (POSIX path of argFilePath) as text
    set ocidFilePathStr to refMe's NSString's stringWithString:(argFilePath)
    set ocidArgFilePath to ocidFilePathStr's stringByStandardizingPath()
  else if (class of argFilePath) is «class furl» then
log "エリアスfurlファイルパス"
    set aliasFilePath to argFilePath as alias
    set strArgFilePath to (POSIX path of argFilePath) as text
    set ocidFilePathStr to refMe's NSString's stringWithString:(argFilePath)
    set ocidArgFilePath to ocidFilePathStr's stringByStandardizingPath()
  else if (className() of argFilePath as text) contains "NSCFString" then
log "NSStringファイルパス"
    set ocidArgFilePath to argFilePath's stringByStandardizingPath()
  else if (className() of argFilePath as text) contains "NSPathStore" then
log "NSPathStore2ファイルパス"
    set ocidArgFilePath to argFilePath
  else if (className() of argFilePath as text) contains "NSURL" then
log "NSURLファイルパス"
    set ocidArgFilePath to argFilePath's |path|
  end if
  ####
  set appFileManager to refMe's NSFileManager's defaultManager()
  set boolExists to appFileManager's fileExistsAtPath:(ocidArgFilePath) isDirectory:(false)
  #
  if boolExists = true then
    ##ダイアログを前面に
    set strName to (name of current application) as text
    if strName is "osascript" then
      tell application "Finder" to activate
    else
      tell current application to activate
    end if
    set strMes to "上書きします?" as text
    try
      set objResponse to (display alert strMes buttons {"上書きする", "処理を中止する", "ファイル名を変更"} default button "上書きする" cancel button "処理を中止する" as informational giving up after 20)
    on error
log "処理を中止しました"
return "処理を中止しました"
      error number -128
    end try
    if true is equal to (gave up of objResponse) then
log "時間切れですやりなおしてください"
return "時間切れですやりなおしてください"
      error number -128
    end if
    if "上書きする" is equal to (button returned of objResponse) then
log "上書き保存します"
      set ocidReturnFilePath to ocidArgFilePath
    else if "ファイル名を変更" is equal to (button returned of objResponse) then
log "ファイル名を変更"
      set ocidContainerDirFilePath to ocidArgFilePath's stringByDeletingLastPathComponent()
      set strFileName to ocidArgFilePath's lastPathComponent() as text
      set aliasContainerDirPath to (POSIX file (ocidContainerDirFilePath as text)) as alias
      ##
      set strPromptText to "名前を決めてください" as text
      set strMesText to "名前を決めてください" as text
      ###ファイル名 ダイアログ
      set aliasFilePath to (choose file name strMesText default location aliasContainerDirPath default name strFileName with prompt strPromptText) as «class furl»
      set strFilePath to (POSIX path of aliasFilePath) as text
      set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
      set ocidReturnFilePath to ocidFilePathStr's stringByStandardizingPath()
    else if "処理を中止する" is equal to (button returned of objResponse) then
return "処理を中止しました"
    else
return "エラーしました"
      error number -128
    end if
  else if boolExists = false then
log "そのままファイル生成"
    set ocidReturnFilePath to ocidArgFilePath
  end if
return ocidReturnFilePath
  
end doChkExists

|

quoted form と quote


【スクリプトエディタで開く】|

# APOSTROPHE
set strText to (quoted form of "サンプル") as string
log strText
-->(*'サンプル'*)

set strText to ("'" & "サンプル" & "'") as string
log strText
-->(*'サンプル'*)

# QUOTATION MARK
set strText to (quote & "サンプル" & quote) as string
log strText
-->(*"サンプル"*)

set strText to ("\"" & "サンプル" & "\"") as string
log strText
-->(*"サンプル"*)



|

[as alias list]選択中のファイル・フォルダのUNIXパス


tell application "Finder"

  ####Finderで選択中のアイテムのエリアスのリスト

  set listFinderSelection to selection as alias list

end tell

###クリップボードに入れる値の初期化

set strPathList to "" as text

###リストの数だけ繰り返し

repeat with itemFinderSelection in listFinderSelection

  ###エリアスで確定

  set aliasFinderSelection to itemFinderSelection as alias

  ###UNIXパスにする

  set strfilePath to (get POSIX path of itemFinderSelection)

  ###テキストで格納

  set strPathList to strPathList & strfilePath & "\r" as text

end repeat

###クリップボードに格納

set the clipboard to strPathList

log strPathList



|

[Basic]class «class furl» 実体が無くてもエラーにならないエリアス

Alias形式のパスなんですが
実体が無くてもエラーにならない仕様です。
保存先のパス等、先に決めておきたい場合に便利です

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSURL : a reference to refMe's NSURL


set PayloadDisplayName to "com.apple.loginwindow"


set strRelativePath to ("~/Desktop/") as text
set ocidRelativePath to refNSString's stringWithString:strRelativePath
set ocidFullPath to ocidRelativePath's stringByStandardizingPath()
set ocidFullPathURL to refMe's NSURL's fileURLWithPath:ocidFullPath
set aliasFullPathURL to ocidFullPathURL as alias

set strFileName to ("" & PayloadDisplayName & ".mobileconfig") as text

set aliasSaveFilePath to choose file name with prompt "ファイル名を付けてください" default name strFileName default location (aliasFullPathURL)
log aliasSaveFilePath as «class furl»
-->(*file Macintosh HD:Users::…*)
###実体が無いのにエラーにならない
log aliasSaveFilePath as alias
-->
error "file \"Macintosh HD:Users:…\"のタイプをaliasに変換できません。" number -1700 from file "Macintosh HD:Users:…" to alias
#実体が無いのでエラーになる

|

[delay]一定期間経過後にアプリケーションを終了する

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

######ログ表示
doLogView()

property objMe : a reference to current application

set recordReturn to display dialog "選択したアプリケーションをX分後に終了します" default answer "60"
log recordReturn

set numMin to text returned of recordReturn as number
log numMin as number

set aliasAppDir to path to applications folder from local domain as alias
log aliasAppDir

set aliasAppPath to choose file with prompt "アプリケーションを選んでください" default location aliasAppDir
log aliasAppPath as alias


set numSec to 60 * numMin as number
log numSec as number

delay numSec

tell application "Finder"
set strShortName to short name of (info for aliasAppPath) as text
end tell

tell application strShortName to quit



#########################ログ表示
to doLogView()

tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
end if
end repeat

end doLogView
#########################

|

[NSURL]Uniform Type Identifier(UTI)の取得

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

######ログ表示
doLogView()

property objMe : a reference to current application
property objNSString : a reference to objMe's NSString
property objNSURL : a reference to objMe's NSURL



property objNSNotFound : a reference to 9.22337203685477E+18 + 5807


set aliasFilePath to (choose file) as alias
log aliasFilePath as alias
log class of aliasFilePath

set strFilePath to POSIX path of aliasFilePath as text
log strFilePath as text
log class of strFilePath

set ocidFileNsUrl to objNSURL's fileURLWithPath:strFilePath
log ocidFileNsUrl as text
log ocidFileNsUrl's className() as text

set {boolResult, ocidContentType} to ocidFileNsUrl's getResourceValue:(reference) forKey:(objMe's NSURLContentTypeKey) |error|:(missing value)

if ocidContentType is not (missing value) then
log ocidContentType's className() as text
###ここにUTIが入ります
set strUTItype to ocidContentType's identifier as text
log strUTItype as text
end if


#########################ログ表示
to doLogView()

tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
end if
end repeat

end doLogView
#########################

|

[Basic]rest of characters log rest of words

set strText to "ABCD EFGH" as text

###1文字目を削除
log rest of characters of strText

###1ワード名を削除
log rest of words of strText

###逆順
log reverse of characters of strText

###取り出し
log characters 1 thru 2 of strText

###取り出し
log text 1 thru 2 of strText

|

[Basic]MimeTypeとUTI

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions
use framework "UniformTypeIdentifiers"


property objMe : a reference to current application
property objNSString : a reference to objMe's NSString
property objNSURL : a reference to objMe's NSURL
property objUTType : a reference to objMe's UTType


####ダイアログで使うデフォルトロケーション
tell application "Finder"
set aliasDefaultLocation to container of (path to me) as alias
##set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell
####MIMEリスト
set listMimeType to {"image/jpeg", "image/png", "image/webp", "image/heic", "image/bmp"}

####UTIリスト
set listUTI to {"public.jpeg", "public.png", "public.webp", "public.heic", "public.bmp"}

####ダイアログを出す
set aliasFilePath to (choose file with prompt "ファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias

####ファイルのインフォメーションを取得
set objInfoFor to info for aliasFilePath
tell objInfoFor
###UTIを取得
set strTypeIdentifier to type identifier as text
###拡張子を取得
set strExtension to name extension as text
end tell

####拡張子からUTI取得
set ocidUTType to objUTType's typeWithFilenameExtension:strExtension
set strUTI to ocidUTType's identifier as text

####UTIからMIME取得
set ocidFileMimeType to ocidUTType's preferredMIMEType()
set strFileMimeType to ocidFileMimeType as text

####MIMEリストを順番に
repeat with objMimeType in listMimeType
set strMimeType to objMimeType as text
####リストの項目と照合
if strFileMimeType is strMimeType then
log strMimeType & "である"
else
log strMimeType & "これではない"
end if
end repeat

|

[text]文字列の基本

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

######ログ表示
doLogView()

############################

set strSampleText to "12345678901234567890" as text

############################
### characterを使う
####7番目の文字
log seventh character of strSampleText

log 7th character of strSampleText

log item 7 of (every character of strSampleText)

log seventh item of (every character of strSampleText)

log 7th item of (every character of strSampleText)

log 19th character of strSampleText

#### itemを使う
####7番目のアイテム
log item 7 of strSampleText

log seventh item of strSampleText

log 7th item of strSampleText

log item 7 of (every item of strSampleText)

log seventh item of (every item of strSampleText)

log 7th item of (every item of strSampleText)

log 19th item of strSampleText


############################

####3文字目から7文字目まで
log characters 3 thru 7 of strSampleText as list

log characters 3 thru 7 of strSampleText as string

log characters 3 thru 7 of strSampleText as text

####3文字目から7文字目まで
log items 3 thru 7 of strSampleText as list

log items 3 thru 7 of strSampleText as string

log items 3 thru 7 of strSampleText as text

############################

####7文字目から最後まで
log characters 7 thru end of strSampleText as list

log characters 7 thru end of strSampleText as string

log characters 7 thru end of strSampleText as text

####7文字目から最後まで
log items 7 thru end of strSampleText as list

log items 7 thru end of strSampleText as string

log items 7 thru end of strSampleText as text

############################
####数える

log length of strSampleText

log number of strSampleText

log (count of strSampleText)



to doLogView()
#########################ログ表示
tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
end if
end repeat
#########################
end doLogView

|

[URL]クエリー部分の置き換え

Youtubeのダウンロード時に使った方法



set strUrl to "https://www.hoo.hoge.com/videoplayback?AA=aaaa&BB=bbb&C=ccc&DD=ddd&EE=eee&FF=fff&GG=ggg&range=88888-88888&mime=audio%2Fwebm"

### 『&』の文字で区切る
set AppleScript's text item delimiters to "&"
### 区切られた文字をリストにする
set listUrl to every text item of strUrl as list
### 区切り文字を戻す
set AppleScript's text item delimiters to ""

####置き換え後のURLの初期化
set strNewURL to "" as text
####カウントアップの初期化
set numCntRepeat to 0 as number

####繰り返し
repeat with objUrl in listUrl
###繰り返しのリストをとりあえずテキストとして確定
set strUrlQuery to objUrl as text
####繰り返しで分岐がある場合
if strUrlQuery is "mime=audio%2Fwebm" then
set strFileType to "AudioWebm" as text
else if strUrlQuery is "mime=video%2Fwebm" then
set strFileType to "VideoWebm" as text
else if strUrlQuery is "mime=audio%2Fmp4" then
set strFileType to "AudioMp4" as text
else if strUrlQuery is "mime=video%2Fmp4" then
set strFileType to "VideoMp4" as text
end if
######rangeの置き換え
if objUrl starts with "range=" then
set objUrl to "range=0-999999999999" as text
end if

if numCntRepeat = 0 then
####最初は&でつながない
set strNewURL to (objUrl as text) as text
else
#### 2個目以降は&でつなぐ
set strNewURL to ("" & strNewURL & "&" & objUrl & "") as text
end if
#### カウントアップ
set numCntRepeat to numCntRepeat + 1 as number
end repeat

log strFileType
-->(*AudioWebm*)
log strNewURL
-->(*https://www.hoo.hoge.com/videoplayback?AA=aaaa&BB=bbb&C=ccc&DD=ddd&EE=eee&FF=fff&GG=ggg&range=0-999999999999&mime=audio%2Fwebm*)

|

より以前の記事一覧

その他のカテゴリー

Acrobat Acrobat Annotation Acrobat Dialog Acrobat Form Acrobat JS Acrobat Open Acrobat Plugin Acrobat python Acrobat Reader Acrobat Sequ Acrobat Stamps Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin System Information Admin Tools Admin Users Admin Volumes Adobe Apple AppleScript AppleScript Guide AppleScript Accessibility AppleScript AppKit AppleScript Applications AppleScript AppStore AppleScript Archive AppleScript Attributes AppleScript Automator AppleScript AVAsset AppleScript AVconvert AppleScript AVFoundation AppleScript AVURLAsset AppleScript BackUp AppleScript Barcode AppleScript Bash AppleScript Basic AppleScript Basic Path AppleScript Bluetooth AppleScript BOX AppleScript Browser AppleScript Calendar AppleScript CD/DVD AppleScript Choose AppleScript Chrome AppleScript CIImage AppleScript CloudStorage AppleScript Color AppleScript com.apple.LaunchServices.OpenWith AppleScript Console AppleScript Contacts AppleScript CotEditor AppleScript CURL AppleScript current application AppleScript Date&Time AppleScript delimiters AppleScript Desktop AppleScript Device AppleScript Disk AppleScript do shell script AppleScript Dock AppleScript DropBox AppleScript eMail AppleScript Encode Decode AppleScript Error AppleScript EXIFData AppleScript ffmpeg AppleScript File AppleScript Finder AppleScript Firefox AppleScript Folder AppleScript Fonts AppleScript GIF AppleScript HTML AppleScript Icon AppleScript Illustrator AppleScript Image Events AppleScript Image2PDF AppleScript ImageOptim Applescript iWork AppleScript Javascript AppleScript Jedit AppleScript Json AppleScript Label AppleScript List AppleScript locationd AppleScript LRC AppleScript LSSharedFileList AppleScript m3u8 AppleScript MakePDF AppleScript Map AppleScript Math AppleScript Microsoft AppleScript Microsoft Edge AppleScript Microsoft Excel AppleScript Mobileconfig AppleScript Mouse AppleScript Movie AppleScript Music AppleScript NetWork AppleScript Notes AppleScript NSArray AppleScript NSBitmapImageRep AppleScript NSBundle AppleScript NSCFBoolean AppleScript NSCharacterSet AppleScript NSColor AppleScript NSColorList AppleScript NSData AppleScript NSDictionary AppleScript NSError AppleScript NSEvent AppleScript NSFileAttributes AppleScript NSFileManager AppleScript NSFont AppleScript NSFontManager AppleScript NSImage AppleScript NSIndex AppleScript NSKeyedArchiver AppleScript NSKeyedUnarchiver AppleScript NSLocale AppleScript NSMutableArray AppleScript NSMutableDictionary AppleScript NSMutableString AppleScript NSNotFound AppleScript NSNumber AppleScript NSOpenPanel AppleScript NSPasteboard AppleScript NSPDFImageRep AppleScript NSpoint AppleScript NSPredicate AppleScript NSRange AppleScript NSRegularExpression AppleScript NSRunningApplication AppleScript NSScreen AppleScript NSSize AppleScript NSString AppleScript NSStringCompareOptions AppleScript NSTask AppleScript NSTimeZone AppleScript NSURL AppleScript NSURL File AppleScript NSURLBookmark AppleScript NSURLComponents AppleScript NSURLResourceKey AppleScript NSUserDefaults AppleScript NSUUID AppleScript NSView AppleScript NSWorkspace AppleScript Numbers AppleScript OAuth AppleScript ObjC AppleScript OneDrive AppleScript Osax AppleScript PDF AppleScript PDFAnnotationWidget AppleScript PDFContext AppleScript PDFDisplayBox AppleScript PDFDocumentPermissions AppleScript PDFKit AppleScript PDFnUP AppleScript PDFOutline AppleScript Photos AppleScript Photoshop AppleScript Plist System Events AppleScript PostScript AppleScript prefPane AppleScript Preview AppleScript Python AppleScript QR AppleScript QR Decode AppleScript QuickLook AppleScript QuickTime AppleScript record AppleScript Regular Expression AppleScript Reminders AppleScript ReName AppleScript Repeat AppleScript RTF AppleScript Safari AppleScript SaveFile AppleScript ScreenCapture AppleScript ScreenSaver AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript Sort AppleScript Sound AppleScript Spotlight AppleScript SRT AppleScript StandardAdditions AppleScript stringByApplyingTransform AppleScript System Events AppleScript System Settings AppleScript TemporaryItems AppleScript Terminal AppleScript Text AppleScript Text CSV AppleScript Text TSV AppleScript TextEdit AppleScript Translate AppleScript Trash AppleScript Twitter AppleScript UI AppleScript Unit Conversion AppleScript UTType AppleScript valueForKeyPath AppleScript Video AppleScript VisionKit AppleScript Visual Studio Code AppleScript webarchive AppleScript webp AppleScript Wifi AppleScript XML AppleScript XML EPUB AppleScript XML OPML AppleScript XML Plist AppleScript XML RSS AppleScript XML SVG AppleScript XML TTML AppleScript XML webloc AppleScript YouTube AppleScript Zero Suppress Applications Barcode OnLine Tools CityCode Design iPhone List Logs lsappinfo Memo Music perl PlistBuddy pluginkit postalcode ReadMe SF Symbols character id SF Symbols Entity sips Skype Slack sqlite TCC Tools Typography Video Wacom zoom