NSFileManager

iCloud driveの書類を開く


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# com.cocolog-nifty.quicktimer.icefloe
004#
005#
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "AppKit"
010use scripting additions
011
012property refMe : a reference to current application
013
014##
015set appFileManager to refMe's NSFileManager's defaultManager()
016set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSUserDomainMask))
017set ocidLibraryDirPathURL to ocidURLsArray's firstObject()
018set ocidiCloudDirPathURL to ocidLibraryDirPathURL's URLByAppendingPathComponent:("Mobile Documents") isDirectory:(true)
019set aliasiCloudDirPath to (ocidiCloudDirPathURL's absoluteURL()) as alias
020
021#############################
022#ダイアログ
023set strName to (name of current application) as text
024if strName is "osascript" then
025  tell application "Finder" to activate
026else
027  tell current application to activate
028end if
029set listUTI to {"public.item"}
030set strMes to ("ファイルを選んでください") as text
031set strPrompt to ("ファイルを選んでください") as text
032try
033  ### ファイル選択時
034  set aliasFilePath to (choose file strMes with prompt strPrompt default location (aliasiCloudDirPath) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
035on error
036  log "エラーしました"
037  return "エラーしました"
038end try
039##選んだファイル
040set strFilePath to (POSIX path of aliasFilePath) as text
041set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
042set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
043set ocidTargetFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
044
045##iCloudファイルか?確認
046set listResponse to ocidTargetFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsUbiquitousItemKey) |error| :(reference)
047set boolIsUbiquitou to (item 2 of listResponse)
048#iCloudデータの場合は
049if boolIsUbiquitou is true then
050  log "iCloudデータです"
051  ##まずはダウンロードを試みて
052  set listDone to appFileManager's startDownloadingUbiquitousItemAtURL:(ocidTargetFilePathURL) |error| :(reference)
053  if (item 2 of listDone) is true then
054    log "正常処理"
055  else if (item 2 of listDone) ≠ (missing value) then
056    set strErrorNO to (item 2 of listDone)'s code() as text
057    set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
058    refMe's NSLog("■:" & strErrorNO & strErrorMes)
059    return "エラーしました" & strErrorNO & strErrorMes
060  end if
061end if
062
063
064##エラーがなければ開く
065set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
066set boolDone to appSharedWorkspace's openURL:(ocidTargetFilePathURL)
067
068
AppleScriptで生成しました

|

ファイルのある親フォルダ名をファイル名にする


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#  別名でアプリケーション保存でドロップレットになります
005# com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.6"
008use framework "Foundation"
009use framework "AppKit"
010use scripting additions
011
012property refMe : a reference to current application
013property listUTI : {"public.item"} as list
014
015#################################
016#【1】クリックでオープンした場合
017on run
018  #ダイアログ を前面に
019  set strName to (name of current application) as text
020  if strName is "osascript" then
021    tell application "Finder" to activate
022  else
023    tell current application to activate
024  end if
025  #デフォルトパス
026  set appFileManager to refMe's NSFileManager's defaultManager()
027  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
028  set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
029  set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
030  set strMes to ("ファイルを選んでください") as text
031  set strPrompt to ("ファイルを選んでください") as text
032  try
033    #ダイアログ
034    set listChooseAliasFilePath to (choose file strMes with prompt strPrompt default location (aliasDefaultLocation) of type listUTI with multiple selections allowed without invisibles and showing package contents) as list
035  on error
036    log "エラーしました"
037    return "エラーしました"
038  end try
039  #ファイルリストを次の処理に渡す
040  set boolDone to doPathSender(listChooseAliasFilePath)
041  #戻り値チェック
042  if boolDone is false then
043    display alert "エラーが発生しました" message "エラーが発生しました"
044    return "エラー終了run"
045  else
046    return "処理終了run"
047  end if
048end run
049
050#################################
051#【2】ドロップした場合
052on open listDropAliasFilePath
053  #########【2−1】UTIチェック
054  #サブルーチンに渡すリスト
055  set listAliasFilePath to {} as list
056  #ドロップされたアイテムの数だけ繰り返す
057  repeat with itemDropAliasFilePath in listDropAliasFilePath
058    #エイリアス
059    set aliasItemFilePath to itemDropAliasFilePath as alias
060    tell application "Finder"
061      #Finder情報を取得して
062      set recordInfoFor to info for aliasItemFilePath
063    end tell
064    #UTIを取得
065    set strItemUIT to (type identifier of recordInfoFor) as text
066    #UTIが対象ファイルならリストに追加
067    repeat with itemUTI in listUTI
068      if strItemUIT is itemUTI then
069        copy aliasItemFilePath to end of listAliasFilePath
070      end if
071    end repeat
072  end repeat
073  #########【2−1】KINDチェック
074  set listSendAliasFilePath to {} as list
075  repeat with itemAliasFilePath in listAliasFilePath
076    #処理する判定
077    set boolChkAliasPath to true as boolean
078    try
079      tell application "Finder"
080        set strKind to (kind of itemDropObject) as text
081      end tell
082      if strKind is "アプリケーション" then
083        log "アプリケーションは処理しない"
084        set boolChkAliasPath to false as boolean
085      else if strKind is "ボリューム" then
086        log "ボリュームは処理しない"
087        set boolChkAliasPath to false as boolean
088      else if strKind is "エイリアス" then
089        log "エイリアスは処理しない"
090        set boolChkAliasPath to false as boolean
091      else if strKind is "フォルダ" then
092        log "フォルダは処理しない"
093        set boolChkAliasPath to false as boolean
094      end if
095    on error
096      log "シンボリックリンク等kindを取得できないファイルは処理しない"
097      set boolChkAliasPath to false as boolean
098    end try
099    if boolChkAliasPath is true then
100      copy itemAliasFilePath to end of listSendAliasFilePath
101    end if
102  end repeat
103  #########【2−3】次工程に渡す
104  set boolDone to doPathSender(listSendAliasFilePath)
105  if boolDone is not true then
106    return false
107  else
108    return "処理終了open"
109  end if
110end open
111
112#################################
113#【3】1と2からファイルパスのエイリアスを受け取り
114#処理に順番に渡す
115to doPathSender(argListAliasFilePath)
116  set appFileManager to refMe's NSFileManager's defaultManager()
117  #1回でいい処理はここに記述する
118  
119  ####1ファイルパス毎本処理に渡す
120  repeat with itemAliasFilePath in argListAliasFilePath
121    #本処理に渡す
122    set boolDone to doAction(itemAliasFilePath)
123    #戻り値がエラーだったら?
124    if boolDone is false then
125      tell application "Finder"
126        set strFileName to (name of itemAliasFilePath) as text
127      end tell
128      set strMes to (strFileName & "でエラーになりました") as text
129      display alert "エラーが発生しました" message strMes
130      return strMes
131      #エラーになったところで止める
132    end if
133  end repeat
134  return true
135end doPathSender
136
137#################################
138#【4】実際の処理は全てここ
139to doAction(argAliasFilePath)
140  
141  set appFileManager to refMe's NSFileManager's defaultManager()
142  #ファイルパス
143  set aliasFilePath to argAliasFilePath as alias
144  set strFilePath to (POSIX path of aliasFilePath) as text
145  set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
146  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
147  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:(false))
148  #拡張子
149  set strExtensionName to ocidFilePathURL's pathExtension() as text
150  #親フォルダ
151  set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
152  set ocidDirName to ocidContainerDirPathURL's lastPathComponent()
153  #拡張子抜きの移動先パス
154  set ocidMoveBaseFilePathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:(ocidDirName) isDirectory:(false)
155  #拡張子付きの移動先パス
156  set ocidMoveFilePathURL to ocidMoveBaseFilePathURL's URLByAppendingPathExtension:(strExtensionName)
157  #同名ファイル回避用の連番
158  set numCntRepeat to 2 as number
159  repeat
160    #移動先パス
161    set ocidMoveFilePath to ocidMoveFilePathURL's |path|()
162    #有無チェック
163    set boolExists to appFileManager's fileExistsAtPath:(ocidMoveFilePath) isDirectory:(false)
164    #すでに同名ファイルがある場合
165    if boolExists = true then
166      ##複数ファイルがある場合の処理はここで工夫する
167      set strSetExtension to (numCntRepeat & "." & strExtensionName) as text
168      set ocidMoveFilePathURL to ocidMoveBaseFilePathURL's URLByAppendingPathExtension:(strSetExtension)
169    else if boolExists = false then
170      ##同名ファイルが無いならファイルを移動する
171      set listDone to (appFileManager's moveItemAtURL:(ocidFilePathURL) toURL:(ocidMoveFilePathURL) |error| :(reference))
172      if (item 1 of listDone) is true then
173        return true
174      else if (item 2 of listDone) ≠ (missing value) then
175        set strErrorNO to (item 2 of listDone)'s code() as text
176        set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
177        refMe's NSLog("■:" & strErrorNO & strErrorMes)
178        log "エラーしました" & strErrorNO & strErrorMes
179        return false
180      end if
181    end if
182    #同名ファイル回避用の連番をカウントアップ
183    set numCntRepeat to numCntRepeat + 1 as number
184  end repeat
185  
186  
187  return true
188end doAction
AppleScriptで生成しました

|

[contentsOfDirectoryAtURL]コンテンツURLの収集 第一階層のみ


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#com.cocolog-nifty.quicktimer.icefloe
005#
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "AppKit"
010use scripting additions
011property refMe : a reference to current application
012
013
014##ダウンロードフォルダ
015set appFileManager to refMe's NSFileManager's defaultManager()
016set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDownloadsDirectory) inDomains:(refMe's NSUserDomainMask))
017set ocidDownloadsDirPathURL to ocidURLsArray's firstObject()
018##
019#不可視ファイル無視
020set ocidOption to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
021#収集キー
022set ocidKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
023ocidKeyArray's addObject:(refMe's NSURLPathKey)
024ocidKeyArray's addObject:(refMe's NSURLIsSymbolicLinkKey)
025ocidKeyArray's addObject:(refMe's NSURLIsDirectoryKey)
026ocidKeyArray's addObject:(refMe's NSURLContentTypeKey)
027#URLの収集
028set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidDownloadsDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error| :(reference))
029if (item 2 of listResponse) = (missing value) then
030  set ocidSubPathURLArray to (item 1 of listResponse)
031else if (item 2 of listResponse) ≠ (missing value) then
032  set strErrorNO to (item 2 of listResponse)'s code() as text
033  set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
034  refMe's NSLog("■:" & strErrorNO & strErrorMes)
035  return "エラーしました" & strErrorNO & strErrorMes
036end if
037#必要があればソートしておく
038set ocidURLArraySorted to ocidSubPathURLArray's sortedArrayUsingSelector:("absoluteString")
039#収取したURLの数
040set numCntArray to ocidURLArraySorted's |count|()
041#収集したURLの数だけ繰り返し
042repeat with itemNo from 0 to (numCntArray - 1) by 1
043  #URL取り出し
044  set ocidItemURL to (ocidURLArraySorted's objectAtIndex:(itemNo))
045  #リソース取り出し
046  set listResponse to (ocidItemURL's getResourceValue:(reference) forKey:(refMe's NSURLContentTypeKey) |error| :(reference))
047  if (item 3 of listResponse) = (missing value) then
048    set ocidUTType to (item 2 of listResponse)
049  else if (item 3 of listResponse) ≠ (missing value) then
050    set strErrorNO to (item 3 of listResponse)'s code() as text
051    set strErrorMes to (item 3 of listResponse)'s localizedDescription() as text
052    refMe's NSLog("■:" & strErrorNO & strErrorMes)
053    return "エラーしました" & strErrorNO & strErrorMes
054  end if
055  #UTI
056  set ocidUTI to ocidUTType's identifier()
057  log ocidItemURL's |path| as text
058  log ocidUTI as text
059  
060end repeat
061
062
AppleScriptで生成しました

|

[Skitch]キャッシュをゴミ箱に入れる


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

#!/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

property refMe : a reference to current application

##パス
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidLibraryDirPathURL to ocidURLsArray's firstObject()
set ocidPrefDirPathURL to ocidLibraryDirPathURL's URLByAppendingPathComponent:("Containers/com.skitch.skitch/Data/tmp")
##コンテンツ収集 1階層のみ
set ocidOption to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
set ocidKeyArray to refMe's NSArray's arrayWithArray:({(refMe's NSURLPathKey), (refMe's NSURLIsDirectoryKey), (refMe's NSURLIsSymbolicLinkKey)})
set listSubPathResult to (appFileManager's contentsOfDirectoryAtURL:(ocidPrefDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error|:(reference))
set ocidSubPathURLArray to item 1 of listSubPathResult
###収集したURLの数だけ繰り返し
repeat with itemSubPathURL in ocidSubPathURLArray
  ###ゴミ箱に入れる
  set listDone to (appFileManager's trashItemAtURL:(itemSubPathURL) resultingItemURL:(itemSubPathURL) |error|:(reference))
end repeat


|

[NSFileManager]ファイルのコピー (Acrobatのスタンプデータのバックアップを作成する)


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
(*
バックアップデータ
1:上書き
2:日付を入れる等して個別データ完全
3:差分のみバックアップする 等がありますが
これは、2の日付を入れた個別データ完全バックアップです
*)
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions
property refMe : a reference to current application
######################
##書類フォルダ
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDocumentDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDocumentDirPathURL to ocidURLsArray's firstObject()
set ocidMkDirPathURL to ocidDocumentDirPathURL's URLByAppendingPathComponent:("Adobe/Acrobat/Stamps/") isDirectory:(true)
###フォルダを作っておく
###フォルダのアトリビュート
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(493) forKey:(refMe's NSFilePosixPermissions)
set listDone to (appFileManager's createDirectoryAtURL:(ocidMkDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference))
###保存先となるパス
set strDateNo to doGetDateNo({"yyyyMMdd", 1}) as text
set ocidSaveDirPathURL to (ocidMkDirPathURL's URLByAppendingPathComponent:(strDateNo) isDirectory:(true))
######################
###スタンプフォルダ
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidLibraryDirPathURL to ocidURLsArray's firstObject()
set ocidDcDirPathURL to ocidLibraryDirPathURL's URLByAppendingPathComponent:("Adobe/Acrobat/DC/") isDirectory:(true)
set ocidStampDirPathURL to (ocidDcDirPathURL's URLByAppendingPathComponent:("Stamps") isDirectory:(true))

######################
###ファイルコピー
set listDone to appFileManager's copyItemAtURL:(ocidStampDirPathURL) toURL:(ocidSaveDirPathURL) |error|:(reference)
### ファイルのコピーに失敗した場合のエラー表示
if (item 1 of listDone) is false then
  set ocidNSErrorData to (item 2 of listDone)
  log "エラーコード:" & ocidNSErrorData's code() as text
  log "エラードメイン:" & ocidNSErrorData's domain() as text
  log "Description:" & ocidNSErrorData's localizedDescription() as text
  log "FailureReason:" & ocidNSErrorData's localizedFailureReason() as text
return "コピーに失敗しました"
end if

######################
###保存先を開く
set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
set boolDone to appSharedWorkspace's selectFile:(ocidSaveDirPathURL's |path|()) inFileViewerRootedAtPath:(ocidMkDirPathURL's |path|())
###エラーしたらFinderで開く
if boolDone is false then
  set aliasOpenDirPath to (ocidMkDirPathURL's absoluteURL()) as alias
  tell application "Finder"
    open folder aliasOpenDirPath
  end tell
return "エラーしました"
end if



################################
# 日付 doGetDateNo(argDateFormat,argCalendarNO)
# argCalendarNO 1 NSCalendarIdentifierGregorian 西暦
# argCalendarNO 2 NSCalendarIdentifierJapanese 和暦
################################
to doGetDateNo({argDateFormat, argCalendarNO})
  ##渡された値をテキストで確定させて
  set strDateFormat to argDateFormat as text
  set intCalendarNO to argCalendarNO as integer
  ###日付情報の取得
  set ocidDate to current application's NSDate's |date|()
  ###日付のフォーマットを定義(日本語)
  set ocidFormatterJP to current application's NSDateFormatter's alloc()'s init()
  ###和暦 西暦 カレンダー分岐
  if intCalendarNO = 1 then
    set ocidCalendarID to (current application's NSCalendarIdentifierGregorian)
  else if intCalendarNO = 2 then
    set ocidCalendarID to (current application's NSCalendarIdentifierJapanese)
  else
    set ocidCalendarID to (current application's NSCalendarIdentifierISO8601)
  end if
  set ocidCalendarJP to current application's NSCalendar's alloc()'s initWithCalendarIdentifier:(ocidCalendarID)
  set ocidTimezoneJP to current application's NSTimeZone's alloc()'s initWithName:("Asia/Tokyo")
  set ocidLocaleJP to current application's NSLocale's alloc()'s initWithLocaleIdentifier:("ja_JP_POSIX")
  ###設定
ocidFormatterJP's setTimeZone:(ocidTimezoneJP)
ocidFormatterJP's setLocale:(ocidLocaleJP)
ocidFormatterJP's setCalendar:(ocidCalendarJP)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterNoStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterShortStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterMediumStyle)
  # ocidFormatterJP's setDateStyle:(current application's NSDateFormatterLongStyle)
ocidFormatterJP's setDateStyle:(current application's NSDateFormatterFullStyle)
  ###渡された値でフォーマット定義
ocidFormatterJP's setDateFormat:(strDateFormat)
  ###フォーマット適応
  set ocidDateAndTime to ocidFormatterJP's stringFromDate:(ocidDate)
  ###テキストで戻す
  set strDateAndTime to ocidDateAndTime as text
return strDateAndTime
end doGetDateNo

|

[NSFilePosixPermissions]パーミッション変更10進数

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

#!/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


property refMe : a reference to current application
set appFileManager to refMe's NSFileManager's defaultManager()



####ダイアログで使うデフォルトロケーション
tell application "Finder"
  set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell

###ANy
set listUTI to {"public.item"}
####ダイアログを出す
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 strFilePath to POSIX path of aliasFilePath
####ドキュメントのパスをNSString
set ocidFilePath to refMe's NSString's stringWithString:strFilePath
set ocidFilePath to ocidFilePath's stringByStandardizingPath
set ocidNSUrlPath to refMe's NSURL's fileURLWithPath:ocidFilePath


###アトリビュートを取得
set ocidFileAttr to appFileManager's attributesOfItemAtPath:ocidFilePath |error|:(missing value)
log (ocidFileAttr's valueForKey:"NSFilePosixPermissions") as integer

###8進数パーミッション値を10進数に変換
set strPemission to doOct2Dem(777)
####パス指定でパーミッション変更 10進数指定
appFileManager's setAttributes:{NSFilePosixPermissions:strPemission} ofItemAtPath:ocidFilePath |error|:(reference)

###511になれば777
###アトリビュートを取得
set ocidFileAttr to appFileManager's attributesOfItemAtPath:ocidFilePath |error|:(missing value)
log (ocidFileAttr's valueForKey:"NSFilePosixPermissions") as integer


###################################
#####パーミッション 8進→10進
(*
###主要なモード NSFilePosixPermissions
777-->511
775-->509
770-->504
755-->493
750-->488
700-->448
555-->365
333-->219
*)
###################################

to doOct2Dem(argOctNo)
  set strOctalText to argOctNo as text
  set num3Line to first item of strOctalText as number
  set num2Line to 2nd item of strOctalText as number
  set num1Line to last item of strOctalText as number
  set numDecimal to (num3Line * 64) + (num2Line * 8) + (num1Line * 1)
  return numDecimal as integer
end doOct2Dem

|

[Folder]新しいフォルダを作る

#!/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


property refNSDate : a reference to refMe's NSDate

property refNSCalendar : a reference to refMe's NSCalendar

property refNSTimeZone : a reference to refMe's NSTimeZone

property refNSDateFormatter : a reference to refMe's NSDateFormatter



set objFileManager to refMe's NSFileManager's defaultManager()





set ocidDesktopDirPathURL to (objFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))


set aliasDefaultLocation to ocidDesktopDirPathURL as alias

set strDefaultName to doGetDateNo("yyyyMMdd") as text

set strPromptText to "名前を決めてください" as text


set aliasPath to (choose file name default location aliasDefaultLocation default name strDefaultName with prompt strPromptText) as «class furl»

####パステキスト

set strFilePathText to POSIX path of aliasPath as text

###String

set ocidFilePath to (refNSString's stringWithString:strFilePathText)

###絶対パスで

set ocidFilePathString to ocidFilePath's stringByStandardizingPath

###NSURL

set ocidFilePathURL to (refNSURL's alloc()'s initFileURLWithPath:ocidFilePathString isDirectory:true)


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

#####属性を指定しておく

set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0

set numUID to user ID of (system info) as number

###所有者ID

ocidAttrDict's setValue:numUID forKey:(refMe's NSFileOwnerAccountID)

###グループID

ocidAttrDict's setValue:80 forKey:(refMe's NSFileGroupOwnerAccountID)

#####NSFileGroupOwnerAccountID

(* ゲストのGID

80-->admin

20-->staff

201-->_guest

99-->_unknown

-2-->nobody

*)

####パーミッション

set numPermissionDem to doOct2Dem(777) as integer

log numPermissionDem

ocidAttrDict's setValue:numPermissionDem forKey:(refMe's NSFilePosixPermissions)

###作るフォルダの属性

(*

###主要なモード NSFilePosixPermissions

777-->511

775-->509

770-->504

755-->493

750-->488

700-->448

555-->365

333-->219

*)

ocidAttrDict's setValue:(refMe's NSFileProtectionNone) forKey:(refMe's NSFileProtectionKey)

ocidAttrDict's setValue:0 forKey:(refMe's NSFileAppendOnly)


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

###フォルダを作る

set listBoolMakeDir to objFileManager's createDirectoryAtURL:(ocidFilePathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)


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

####ラベルを指定する

(*

0:ラベル無し

1:グレー

2:グリーン

3:パープル

4:ブルー

5:イエロー

6:レッド

7:オレンジ

*)

ocidFilePathURL's setResourceValue:7 forKey:(refMe's NSURLLabelNumberKey) |error|:(reference)

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

####コメントの追加

tell application "Finder" to set comment of item aliasPath to strDefaultName






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

#####日付

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

to doGetDateNo(strDateFormat)

  ####日付情報の取得

  set ocidDate to refNSDate's |date|()

  ###日付のフォーマットを定義

  set ocidNSDateFormatter to refNSDateFormatter's alloc()'s init()

  ocidNSDateFormatter's setLocale:(refMe's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")

  ocidNSDateFormatter's setDateFormat:strDateFormat

  set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate

  set strDateAndTime to ocidDateAndTime as text

  return strDateAndTime

end doGetDateNo



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

#####パーミッション 8進→10進

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

to doOct2Dem(argOctNo)

  set strOctalText to argOctNo as text

  set num3Line to first item of strOctalText as number

  set num2Line to 2nd item of strOctalText as number

  set num1Line to last item of strOctalText as number

  set numDecimal to (num3Line * 64) + (num2Line * 8) + (num1Line * 1)

  return numDecimal

end doOct2Dem


|

[trashItemAtURL]フォルダの中身をゴミ箱に入れる

#!/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 aliasDefaultLocation to (path to desktop folder from user domain) as alias
###ダイアログテキスト
set strPromptText to "入力フォルダを選んでください"
try
set listResponse to (choose folder strPromptText with prompt strPromptText default location aliasDefaultLocation without multiple selections allowed, invisibles and showing package contents) as list
on error
log "エラーしました"
return
end try
###エリアス
set aliasDirPath to (item 1 of listResponse) as alias
###UNIXパス
set strFilePathText to POSIX path of aliasDirPath as text

###この指定でもOK
###set strFilePathText to "~/Desktop/名称未設定フォルダ"

###String
set ocidFilePath to (refNSString's stringWithString:strFilePathText)
###絶対パスで
set ocidFilePathString to ocidFilePath's stringByStandardizingPath
###NSURL
set ocidFilePathURL to (refNSURL's alloc()'s initFileURLWithPath:ocidFilePathString isDirectory:true)


###実行
doGo2TrashDirContentsURL(ocidFilePathURL)



################################
####フォルダの中身をゴミ箱へ入れる
################################
on doGo2TrashDirContentsURL(ocidDirUrl)
###ファイルマネージャー初期化
set objFileManager to refMe's NSFileManager's defaultManager()
################################
####渡された値がNSURL以外の場合の処理
try
set strClassName to class of ocidDirUrl as text
####渡された値がテキストだったら
if strClassName is "text" then
set strDirUrl to ocidDirUrl as text
####渡された値がエイリアスだったら
else if strClassName is "alias" then
set strDirPath to POSIX path of ocidDirUrl as text
end if
set ocidFilePath to (refNSString's stringWithString:strDirPath)
set ocidFilePathString to ocidFilePath's stringByStandardizingPath
set ocidDirPathURL to (refNSURL's alloc()'s initFileURLWithPath:ocidFilePathString isDirectory:true)
on error
######ocid形式の値だったら
set strClassName to ocidDirUrl's className() as text
###テキストなら
if strClassName contains "NSCFString" then
set ocidFilePathString to ocidDirUrl's stringByStandardizingPath
set ocidDirPathURL to (refNSURL's alloc()'s initFileURLWithPath:ocidFilePathString isDirectory:true)
###NSURLなら
else if strClassName is "NSURL" then
set ocidDirPathURL to ocidDirUrl
else
error "NSURLを指定してください" number -9999
return
end if
end try
################################
####渡されたパスが無い場合はエラー
set ocidFilePathString to ocidDirPathURL's |path|()
set boolFolderExists to (objFileManager's fileExistsAtPath:ocidFilePathString isDirectory:true)
if boolFolderExists is false then
log "パス先が実在しません"
####パス先ない場合は作っておく
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:511 forKey:(refMe's NSFilePosixPermissions)

set listBoolMakeDir to objFileManager's createDirectoryAtURL:(ocidDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
return
end if
################################
####ディレクトリか?の判断 ファイルならエラーで止める
set ocidResultArray to ocidDirPathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsDirectoryKey) |error|:(reference)
if (item 3 of ocidResultArray) is not (missing value) then
doGetErrorData(item 3 of ocidResultArray)
end if
set ocidResultValue to item 2 of ocidResultArray
-->false
set ocidFalse to (refMe's NSNumber's numberWithBool:false)'s boolValue
if ocidResultValue is ocidFalse then
##error "パス先がファイルですディレクトリを指定してください" number -9999
log "パス先がファイルですディレクトリを指定してください"
return
end if
##################################
##内包リスト
set listResult to objFileManager's contentsOfDirectoryAtURL:ocidDirPathURL includingPropertiesForKeys:{refMe's NSURLPathKey} options:0 |error|:(reference)
###エラー発生時
if (item 2 of listResult) is not (missing value) then
doGetErrorData(item 2 of listResult)
end if
###結果
set ocidPathArray to item 1 of listResult
repeat with itemPathArray in ocidPathArray
set ocidPathArrayURL to itemPathArray
##ゴミ箱に入れる
set listResult to (objFileManager's trashItemAtURL:ocidPathArrayURL resultingItemURL:(missing value) |error|:(reference))
###エラー発生時
if (item 2 of listResult) is not (missing value) then
doGetErrorData(item 2 of listResult)
end if

end repeat

end doGo2TrashDirContentsURL







to doGetErrorData(ocidNSErrorData)
#####個別のエラー情報
log "エラーコード:" & ocidNSErrorData's code() as text
log "エラードメイン:" & ocidNSErrorData's domain() as text
log "Description:" & ocidNSErrorData's localizedDescription() as text
log "FailureReason:" & ocidNSErrorData's localizedFailureReason() as text
log ocidNSErrorData's localizedRecoverySuggestion() as text
log ocidNSErrorData's localizedRecoveryOptions() as text
log ocidNSErrorData's recoveryAttempter() as text
log ocidNSErrorData's helpAnchor() as text
set ocidNSErrorUserInfo to ocidNSErrorData's userInfo()
set ocidAllValues to ocidNSErrorUserInfo's allValues() as list
set ocidAllKeys to ocidNSErrorUserInfo's allKeys() as list
repeat with ocidKeys in ocidAllKeys
if (ocidKeys as text) is "NSUnderlyingError" then
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedDescription() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedFailureReason() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoverySuggestion() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoveryOptions() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s recoveryAttempter() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s helpAnchor() as text
else
####それ以外の値はそのままテキストで読める
log (ocidKeys as text) & ": " & (ocidNSErrorUserInfo's valueForKey:ocidKeys) as text
end if
end repeat

end doGetErrorData

|

[NSDirectoryEnumerationSkip]enumeratorAtURL:includingPropertiesForKeys:options:XerrorHandler:

enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:
options:の後の数値

#!/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


property refMe : a reference to current application


log refMe's NSDirectoryEnumerationSkipsHiddenFiles as integer
(*4*)
log refMe's NSDirectoryEnumerationSkipsPackageDescendants as integer
(*2*)
log refMe's NSDirectoryEnumerationSkipsSubdirectoryDescendants as integer
(*1*)

|

[NSSearchPath]ユーザーデスクトップフォルダーへのパス

#!/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 refNSArray : a reference to refMe's NSArray
set objFileManager to refMe's NSFileManager's defaultManager()

set ocidDeskTopDirArray to refMe's NSSearchPathForDirectoriesInDomains(refMe's NSDesktopDirectory, refMe's NSUserDomainMask, true)

log className() of ocidDeskTopDirArray as text
-->(*__NSSingleObjectArrayI*)

set strUserDesktopPath to (ocidDeskTopDirArray's firstObject()) as text
set strUserDesktopPath to (ocidDeskTopDirArray's objectAtIndex:0) as text

|

より以前の記事一覧

その他のカテゴリー

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