NSFileAttributes

[NSURLAttributeModificationDateKey]Finder情報の取得(ファイル)


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004#
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "UniformTypeIdentifiers"
009use framework "AppKit"
010
011use scripting additions
012property refMe : a reference to current application
013
014set appFileManager to refMe's NSFileManager's defaultManager()
015
016set strName to (name of current application) as text
017if strName is "osascript" then
018  tell application "Finder" to activate
019else
020  tell current application to activate
021end if
022set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
023set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
024set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
025set listUTI to {"public.item"} as list
026set strMes to ("ファイルを選んでください") as text
027set strPrompt to ("ファイルを選んでください") as text
028try
029  set aliasFilePath to (choose file strMes with prompt strPrompt default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
030on error
031  log "エラーしました"
032  return "エラーしました"
033end try
034set strFilePath to (POSIX path of aliasFilePath) as text
035
036set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
037set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
038set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
039set ocidFileName to ocidFilePathURL's lastPathComponent()
040#
041set listResponse to ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLContentTypeKey) |error| :(reference)
042set ocidUTType to (item 2 of listResponse)
043set ocidUTIArray to (ocidUTType's supertypes())'s allObjects()
044set ocidUTTypeString to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
045repeat with itemUTI in ocidUTIArray
046  (ocidUTTypeString's appendString:(itemUTI's identifier()))
047  (ocidUTTypeString's appendString:("\n\t\t\t"))
048end repeat
049set ocidUTI to ocidUTType's identifier()
050(ocidUTTypeString's appendString:(ocidUTI))
051(ocidUTTypeString's appendString:("\n"))
052#
053set listResponse to ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLTotalFileSizeKey) |error| :(reference)
054set ocidTotalFileSize to (item 2 of listResponse)
055set numLong to ocidTotalFileSize's unsignedLongLongValue()
056set numByteUnits to 1000 as integer
057set sizeInKB to (numLong / numByteUnits)
058set sizeInMB to (numLong / (numByteUnits * numByteUnits))
059set sizeInGB to (numLong / (numByteUnits * numByteUnits * numByteUnits))
060set sizeInTB to (numLong / (numByteUnits * numByteUnits * numByteUnits * numByteUnits))
061if (sizeInTB as integer) > 0 then
062  set strTotalFileSize to ((sizeInTB as integer) & " TB") as text
063else if (sizeInGB as integer) > 0 then
064  set strTotalFileSize to ((sizeInGB as integer) & " GB") as text
065else if (sizeInMB as integer) > 0 then
066  set strTotalFileSize to ((sizeInMB as integer) & " MB") as text
067else
068  set strTotalFileSize to ((sizeInKB as integer) & " KB") as text
069end if
070set strRealFileSize to ((numLong as integer) & " Bytes") as text
071#
072set listResponse to ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLTotalFileAllocatedSizeKey) |error| :(reference)
073set ocidAllocatedSize to (item 2 of listResponse)
074set numLong to ocidAllocatedSize's unsignedLongLongValue()
075set numByteUnits to 1000 as integer
076set sizeInKB to (numLong / numByteUnits)
077set sizeInMB to (numLong / (numByteUnits * numByteUnits))
078set sizeInGB to (numLong / (numByteUnits * numByteUnits * numByteUnits))
079set sizeInTB to (numLong / (numByteUnits * numByteUnits * numByteUnits * numByteUnits))
080if (sizeInTB as integer) > 0 then
081  set strAllocatedSize to ((sizeInTB as integer) & " TB") as text
082else if (sizeInGB as integer) > 0 then
083  set strAllocatedSize to ((sizeInGB as integer) & " GB") as text
084else if (sizeInMB as integer) > 0 then
085  set strAllocatedSize to ((sizeInMB as integer) & " MB") as text
086else if (sizeInKB as integer) > 0 then
087  set strAllocatedSize to ((sizeInKB as integer) & " KB") as text
088else
089  set strAllocatedSize to ((numLong as integer) & " Bytes") as text
090end if
091#
092set listResponse to ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLCreationDateKey) |error| :(reference)
093set ocidCreationDate to (item 2 of listResponse)
094set strCreationDate to (ocidCreationDate as date) as text
095#
096set listResponse to ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLContentModificationDateKey) |error| :(reference)
097set ocidModificationDate to (item 2 of listResponse)
098set strModificationDate to (ocidModificationDate as date) as text
099#
100set listResponse to ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLContentAccessDateKey) |error| :(reference)
101set ocidAccessDate to (item 2 of listResponse)
102set strAccessDate to (ocidAccessDate as date) as text
103#
104set listResponse to ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLAttributeModificationDateKey) |error| :(reference)
105set ocidAttributeDate to (item 2 of listResponse)
106set strAttributeDate to (ocidAttributeDate as date) as text
107#
108set listResponse to appFileManager's attributesOfItemAtPath:(ocidFilePath) |error| :(reference)
109set ocidAttarDict to (item 1 of listResponse)
110set ocidOwnerAccount to ocidAttarDict's valueForKey:(refMe's NSFileOwnerAccountName)
111set ocidGroupOwner to ocidAttarDict's valueForKey:(refMe's NSFileGroupOwnerAccountName)
112set ocidPosixPermissionsDec to ocidAttarDict's valueForKey:(refMe's NSFilePosixPermissions)
113#
114set numPermissionsDec to (ocidPosixPermissionsDec as text) as number
115set numDecNo to numPermissionsDec as number
116set numDiv1 to (numDecNo div 8) as number
117set numMod1 to (numDecNo mod 8) as number
118set numDiv2 to (numDiv1 div 8) as number
119set numMod2 to (numDiv1 mod 8) as number
120set numDiv3 to (numDiv2 div 8) as number
121set numMod3 to (numDiv2 mod 8) as number
122set strOctal to (numMod3 & numMod2 & numMod1) as text
123set numPosixPermissionsOct to strOctal as number
124
125#
126set ocidExtendedAttriDec to ocidAttarDict's objectForKey:("NSFileExtendedAttributes")
127set ocidAllKeys to ocidExtendedAttriDec's allKeys()
128set strAttarItems to (ocidAllKeys's componentsJoinedByString:("\n\t\t")) as text
129#
130set ocidExtendedAttriDec to ocidAttarDict's objectForKey:("NSFileExtendedAttributes")
131set ocidAllKeys to ocidExtendedAttriDec's allKeys()
132#
133set boolContain to ocidAllKeys's containsObject:("com.apple.metadata:kMDItemFinderComment")
134if boolContain is true then
135  set ocidSwiftData to ocidExtendedAttriDec's objectForKey:("com.apple.metadata:kMDItemFinderComment")
136  set appPlistSerial to refMe's NSPropertyListSerialization
137  set ocidFormat to refMe's NSPropertyListXMLFormat_v1_0
138  set ocidOption to refMe's NSPropertyListMutableContainersAndLeaves
139  set listResponse to appPlistSerial's propertyListWithData:(ocidSwiftData) options:(ocidOption) format:(ocidFormat) |error| :(reference)
140  set ocidNSSwiftDataString to (item 1 of listResponse)
141  set strFinderComment to ocidNSSwiftDataString as text
142else
143  set strFinderComment to ""
144end if
145
146###########
147set ocidOutputString to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
148(ocidOutputString's appendString:("ファイルパス名: "))
149(ocidOutputString's appendString:(ocidFileName))
150(ocidOutputString's appendString:("\n"))
151(ocidOutputString's appendString:("ファイルパス: "))
152(ocidOutputString's appendString:(ocidFilePath))
153(ocidOutputString's appendString:("\n"))
154(ocidOutputString's appendString:("ファイルタイプ: "))
155(ocidOutputString's appendString:(ocidUTTypeString))
156(ocidOutputString's appendString:("\n"))
157(ocidOutputString's appendString:("ファイルサイズ: "))
158(ocidOutputString's appendString:(strTotalFileSize))
159(ocidOutputString's appendString:("\n"))
160(ocidOutputString's appendString:("使用ディスクサイズ: "))
161(ocidOutputString's appendString:(strAllocatedSize))
162(ocidOutputString's appendString:("\n"))
163(ocidOutputString's appendString:("実サイズ: "))
164(ocidOutputString's appendString:(strRealFileSize))
165(ocidOutputString's appendString:("\n"))
166(ocidOutputString's appendString:("\n"))
167(ocidOutputString's appendString:("拡張属性: "))
168(ocidOutputString's appendString:(strAttarItems))
169(ocidOutputString's appendString:("\n"))
170(ocidOutputString's appendString:("\n"))
171(ocidOutputString's appendString:("作成日: "))
172(ocidOutputString's appendString:(strCreationDate))
173(ocidOutputString's appendString:("\n"))
174(ocidOutputString's appendString:("修正日: "))
175(ocidOutputString's appendString:(strModificationDate))
176(ocidOutputString's appendString:("\n"))
177(ocidOutputString's appendString:("直近アクセス日: "))
178(ocidOutputString's appendString:(strAccessDate))
179(ocidOutputString's appendString:("\n"))
180(ocidOutputString's appendString:("属性変更日: "))
181(ocidOutputString's appendString:(strAttributeDate))
182(ocidOutputString's appendString:("\n"))
183(ocidOutputString's appendString:("\n"))
184(ocidOutputString's appendString:("所有者: "))
185(ocidOutputString's appendString:(ocidOwnerAccount))
186(ocidOutputString's appendString:("\n"))
187(ocidOutputString's appendString:("グループ: "))
188(ocidOutputString's appendString:(ocidGroupOwner))
189(ocidOutputString's appendString:("\n"))
190(ocidOutputString's appendString:("アクセス権10進数: "))
191(ocidOutputString's appendString:(numPermissionsDec as text))
192(ocidOutputString's appendString:("\n"))
193(ocidOutputString's appendString:("アクセス権8進数: "))
194(ocidOutputString's appendString:(numPosixPermissionsOct as text))
195(ocidOutputString's appendString:("\n"))
196(ocidOutputString's appendString:("\n"))
197(ocidOutputString's appendString:("Finderコメント: "))
198(ocidOutputString's appendString:(strFinderComment))
199(ocidOutputString's appendString:("\n"))
200
201log ocidOutputString as text
202
203##############################
204#####ダイアログ
205##############################
206tell current application
207  set strName to name as text
208end tell
209####スクリプトメニューから実行したら
210if strName is "osascript" then
211  tell application "Finder"
212    activate
213  end tell
214else
215  tell current application
216    activate
217  end tell
218end if
219set aliasIconPath to POSIX file "/System/Library/CoreServices/Finder.app/Contents/Resources/Finder.icns" as alias
220set strMes to "戻り値です"
221try
222  set recordResult to (display dialog strMes with title "戻り値です" default answer (ocidOutputString as text) buttons {"クリップボードにコピー", "終了", "再実行"} default button "再実行" cancel button "終了" giving up after 20 with icon aliasIconPath without hidden answer) as record
223on error
224  return "エラーしました"
225end try
226if (gave up of recordResult) is true then
227  return "時間切れです"
228end if
229##############################
230#####自分自身を再実行
231##############################
232if button returned of recordResult is "再実行" then
233  tell application "Finder"
234    set aliasPathToMe to (path to me) as alias
235  end tell
236  run script aliasPathToMe with parameters "再実行"
237end if
238##############################
239#####値のコピー
240##############################
241if button returned of recordResult is "クリップボードにコピー" then
242  try
243    set strText to text returned of recordResult as text
244    ####ペーストボード宣言
245    set appPasteboard to refMe's NSPasteboard's generalPasteboard()
246    set ocidText to (refMe's NSString's stringWithString:(strText))
247    appPasteboard's clearContents()
248    appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
249  on error
250    tell application "Finder"
251      set the clipboard to strText as text
252    end tell
253  end try
254end if
255
256
257return ocidOutputString as text
258
259
AppleScriptで生成しました

|

[Foundation.__NSSwiftData]Finderコメントの取得(com.apple.metadata:kMDItemFinderComment)


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004#
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "UniformTypeIdentifiers"
009use framework "AppKit"
010
011use scripting additions
012property refMe : a reference to current application
013
014set appFileManager to refMe's NSFileManager's defaultManager()
015
016set strName to (name of current application) as text
017if strName is "osascript" then
018  tell application "Finder" to activate
019else
020  tell current application to activate
021end if
022set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
023set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
024set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
025set listUTI to {"public.item"} as list
026set strMes to ("ファイルを選んでください") as text
027set strPrompt to ("ファイルを選んでください") as text
028try
029  set aliasFilePath to (choose file strMes with prompt strPrompt default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
030on error
031  log "エラーしました"
032  return "エラーしました"
033end try
034##パス
035set strFilePath to (POSIX path of aliasFilePath) as text
036set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
037set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
038##アトリビュート属性の取得
039set appFileManager to refMe's NSFileManager's defaultManager()
040set listResponse to appFileManager's attributesOfItemAtPath:(ocidFilePath) |error| :(reference)
041set ocidAttarDict to (item 1 of listResponse)
042##拡張属性の取得
043set ocidExtendedAttriDec to ocidAttarDict's objectForKey:("NSFileExtendedAttributes")
044set ocidAllKeys to ocidExtendedAttriDec's allKeys()
045##Finderコメントの有無をチェック
046set boolContain to ocidAllKeys's containsObject:("com.apple.metadata:kMDItemFinderComment")
047if boolContain is true then
048  log "Finderコメントあり"
049else
050  return "Finder コメント無し"
051end if
052##Finderコメントがあるなら取得する
053# Foundation.__NSSwiftData
054set ocidSwiftData to ocidExtendedAttriDec's objectForKey:("com.apple.metadata:kMDItemFinderComment")
055# NSPropertyListSerialization
056set ocidFormat to refMe's NSPropertyListXMLFormat_v1_0
057set appPlistSerial to refMe's NSPropertyListSerialization
058set ocidOption to refMe's NSPropertyListMutableContainersAndLeaves
059set listResponse to appPlistSerial's propertyListWithData:(ocidSwiftData) options:(ocidOption) format:(ocidFormat) |error| :(reference)
060set ocidNSSwiftDataString to (item 1 of listResponse)
061return ocidNSSwiftDataString as text
AppleScriptで生成しました

|

[NSFileAttributeKey]アクセス権(属性)を設定する

NSFileImmutable以外は使うことないかな…

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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
(*
パーミッション8進数についてはこちらを参考にしてください
[NSFilePosixPermissions]Permission MODE 8進数 10進数 一覧
https://quicktimer.cocolog-nifty.com/icefloe/2022/10/post-ce59ea.html
パーミンション番号8進数→10進数変換
https://quicktimer.cocolog-nifty.com/icefloe/cat76052288/index.html
*)
#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 strFilePath to ("~/Desktop/テストファイル.txt") as text
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 ocidBlankText to refMe's NSString's stringWithString:("")
set listDone to ocidBlankText's writeToURL:(ocidFilePathURL) atomically:true encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
###アクセス権777-->511
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidFilePath) |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
end if
####################
###フォルダに対してのアクセス権設定
set strDirPath to ("~/Desktop/テストフォルダ/") as text
set ocidDirPathStr to refMe's NSString's stringWithString:(strDirPath)
set ocidDirPath to ocidDirPathStr's stringByStandardizingPath()
set ocidDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidDirPath) isDirectory:true)
###アクセス権777-->511
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listDone to appFileManager's createDirectoryAtURL:(ocidDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |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
end if
####################
###NSFileAppendOnly 追加のみ だが追加したファイルやフォルダを削除できなくなる
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(refMe's NSNumber's numberWithBool:true) forKey:(refMe's NSFileAppendOnly)
#ファイルに追加
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidFilePath) |error|:(reference)
#ディレクトリに追加
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidDirPath) |error|:(reference)
## return "状態確認する場合"
##解除
ocidAttrDict's setValue:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSFileAppendOnly)
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidFilePath) |error|:(reference)
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidDirPath) |error|:(reference)


####################
###NSFileExtensionHidden 拡張子を隠すか?だが Finderの拡張子の表示設定が優先される
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(refMe's NSNumber's numberWithBool:true) forKey:(refMe's NSFileExtensionHidden)
#ファイルに追加
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidFilePath) |error|:(reference)
#ディレクトリに追加
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidDirPath) |error|:(reference)
## return "状態確認する場合"
##解除
ocidAttrDict's setValue:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSFileExtensionHidden)
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidFilePath) |error|:(reference)
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidDirPath) |error|:(reference)


####################
###NSFileImmutable chflagsの uchg相当 ユーザーレベル Findeのロック
###Finder フォルダ ファイルアイコンに鍵がつく
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(refMe's NSNumber's numberWithBool:true) forKey:(refMe's NSFileImmutable)
#ファイルに追加
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidFilePath) |error|:(reference)
#ディレクトリに追加
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidDirPath) |error|:(reference)
## return "状態確認する場合"
##解除
ocidAttrDict's setValue:(refMe's NSNumber's numberWithBool:false) forKey:(refMe's NSFileImmutable)
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidFilePath) |error|:(reference)
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidDirPath) |error|:(reference)


####################
###NSFileProtectionKey ファイルの保護のモードを指定できる
(* 設定できる値は 暗号化の方法
NSFileProtectionComplete
NSFileProtectionCompleteUnlessOpen
NSFileProtectionCompleteUntilFirstUserAuthentication
NSFileProtectionNone
NSFileProtectionCompleteWhenUserInactive
*)
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(refMe's NSFileProtectionCompleteUnlessOpen) forKey:(refMe's NSFileProtectionKey)
#ファイルに追加
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidFilePath) |error|:(reference)
#ディレクトリに追加
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidDirPath) |error|:(reference)
## return "状態確認する場合"
##解除
ocidAttrDict's setValue:(refMe's NSFileProtectionNone) forKey:(refMe's NSFileProtectionKey)
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidFilePath) |error|:(reference)
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidDirPath) |error|:(reference)



return


|

[NSFileManager]Permission ファイル フォルダのアクセス権の設定


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
(*
パーミッション8進数についてはこちらを参考にしてください
[NSFilePosixPermissions]Permission MODE 8進数 10進数 一覧
https://quicktimer.cocolog-nifty.com/icefloe/2022/10/post-ce59ea.html
パーミンション番号8進数→10進数変換
https://quicktimer.cocolog-nifty.com/icefloe/cat76052288/index.html
*)
#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 strFilePath to ("~/Library/Mail/PersistenceInfo.plist") as text
set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
###
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidFilePath) |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
end if
####################
###フォルダに対してのアクセス権設定
set strDirPath to ("~/Library/Mail/") as text
set ocidDirPathStr to refMe's NSString's stringWithString:(strDirPath)
set ocidDirPath to ocidDirPathStr's stringByStandardizingPath()
###
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listDone to appFileManager's setAttributes:(ocidAttrDict) ofItemAtPath:(ocidDirPath) |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
end if

|

フォルダを作って新規テキストファイル


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

#!/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 strText to ("美しい日本語のテキスト") as text
set ocidStrings to refMe's NSString's stringWithString:(strText)
##
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
set ocidSaveDirPathURL to ocidDesktopDirPathURL's URLByAppendingPathComponent:("フォルダの名前")
##
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
###
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:("保存するファイル名.txt")
###
set listDone to ocidStrings's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
###ターミナルで実行できるように755アクセス権にする
set ocidFileAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
# 777-->511 755-->493 700-->448 766-->502
(ocidFileAttrDict's setValue:(493) forKey:(refMe's NSFilePosixPermissions))
set listDone to (appFileManager's setAttributes:(ocidFileAttrDict) ofItemAtPath:(ocidSaveFilePathURL's |path|()) |error|:(reference))

log item 1 of listDone
log item 2 of listDone

|

NSFileExtendedAttributes基本


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

#!/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 strFilePath to "~/Creative Cloud Files" as text
set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()

###通常のAttributes
set listAttributesDict to appFileManager's attributesOfItemAtPath:(ocidFilePath) |error|:(reference)
set ocidAttributesDict to (item 1 of listAttributesDict)
set ocidAllKeyArray to ocidAttributesDict's allKeys()
###
repeat with itemKey in ocidAllKeyArray
  set ocidValue to (ocidAttributesDict's valueForKey:(itemKey))
  log itemKey as text
  if (className() of ocidValue as text) contains "Number" then
    log (ocidAttributesDict's valueForKey:(itemKey)) as integer
  else if (className() of ocidValue as text) contains "Date" then
    log (ocidAttributesDict's valueForKey:(itemKey)) as date
  else if (className() of ocidValue as text) contains "Boolean" then
    log (ocidAttributesDict's valueForKey:(itemKey)) as boolean
  else if (className() of ocidValue as text) contains "String" then
    log (ocidAttributesDict's valueForKey:(itemKey)) as text
  end if
  log "----+----1----+----2----+-----3----+----4----+----5"
end repeat
#####NSFileExtendedAttributesの有無
set ocidExtendAttr to ocidAttributesDict's valueForKey:("NSFileExtendedAttributes")
if ocidExtendAttr is (missing value) then
  log "NSFileExtendedAttributesが無い"
else
  log "NSFileExtendedAttributesがある"
  set ocidExtendAllKeysArray to ocidExtendAttr's allKeys()
  repeat with itemKey in ocidExtendAllKeysArray
    if (itemKey as text) is "com.apple.provenance" then
      log "たぶんアイコン付き"
      
    end if
  end repeat
end if
return





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

#!/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 strFilePath to "~/Desktop/B.pdf"

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

set ocidFilePathStr to (refMe's NSString's stringWithString:strFilePath)
set ocidFilePath to ocidFilePathStr's stringByExpandingTildeInPath()
####アトリビュートを取得
set listResponse to appFileManager's attributesOfItemAtPath:ocidFilePath |error|:(reference)
set ocidAttarDict to item 1 of listResponse
####レコード形式で戻り値がくるのでキーの名前を取得
log (ocidAttarDict's allKeys()) as list
log (count of ocidAttarDict)
####NSFileExtendedAttributesは子要素としてレコード形式なので
set ocidExtendAttr to ocidAttarDict's valueForKey:"NSFileExtendedAttributes"
-->ここがポイントNSFileExtendedAttributesがなければmissing valueが帰ります。
log ocidExtendAttr as list
####同様にレコードのキーを取得して対象をしぼると
log ocidExtendAttr's allKeys() as list





|

パーミッション8進→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 framework "AppKit"
use scripting additions

property refMe : a reference to current application

set aliasIconPath to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/FinderIcon.icns" as alias
set strDefaultAnswer to "666" as text

set strText to "777-->511\n775-->509\n770-->504\n755-->493\n750-->488\n700-->448\n644-->420"

try
  ###ダイアログを前面に出す
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder"
      activate
    end tell
  else
    tell current application
      activate
    end tell
  end if
  set recordResponse to (display dialog strText with title "3桁8進数を入力" default answer strDefaultAnswer buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 20 without hidden answer)
  
on error
  log "エラーしました"
return "エラーしました"
  error number -128
end try
if true is equal to (gave up of recordResponse) then
return "時間切れですやりなおしてください"
  error number -128
end if
if "OK" is equal to (button returned of recordResponse) then
  set strResponse to (text returned of recordResponse) as text
else
  log "エラーしました"
return "エラーしました"
  error number -128
end if

set strDem to doOct2Dem(strResponse)

try
  ###ダイアログを前面に出す
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder"
      activate
    end tell
  else
    tell current application
      activate
    end tell
  end if
  set recordResult to (display alert ("計算結果:" & strDem) buttons {"クリップボードにコピー", "キャンセル", "OK"} default button "OK" cancel button "キャンセル" as informational giving up after 30)
on error
  log "エラーしました"
return
end try

###クリップボードコピー
if button returned of recordResult is "クリップボードにコピー" then
  set strText to strDem as text
  ####ペーストボード宣言
  set appPasteboard to refMe's NSPasteboard's generalPasteboard()
  set ocidText to (refMe's NSString's stringWithString:(strText))
appPasteboard's clearContents()
appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
end if

###################################
#####パーミッション 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



|

ディスクが暗号化されているか?


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

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


####NSFileManagerで属性を収集する
set appFileManager to refMe's NSFileManager's defaultManager()
set listAttrDict to appFileManager's attributesOfItemAtPath:("/") |error|:(reference)
set ocidAttrDict to item 1 of listAttrDict
####NSFileProtectionKeyを確認
set ocidProtectionState to ocidAttrDict's valueForKey:(refMe's NSFileProtectionKey)

if (ocidProtectionState as text) contains "NSFileProtectionNone" then
return "暗号化されていません"
else
return "暗号化されています"
end if
(*
NSFileProtectionComplete
常時暗号化
NSFileProtectionCompleteUntilFirstUserAuthentication
※初回暗号化解除すればアクセス可能
NSFileProtectionCompleteUnlessOpen
ファイルを閉じるときに暗号化
NSFileProtectionNone
暗号化無し
*)
return



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

#!/bin/bash
#com.cocolog-nifty.quicktimer.icefloe
########################

STR_STATUS=$(/usr/bin/fdesetup status)
/bin/echo "$STR_STATUS"
if [[ $STR_STATUS == *On* ]]; then
/bin/echo "暗号化されています"
else
/bin/echo "暗号化されていません"
fi

exit 0

|

NSFileExtendedAttributes削除

xattrにたよるしかない…

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

#!/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 ocidUserDesktopPath to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set aliasDefaultLocation to ocidUserDesktopPath as alias
###アプリケーション限定
set listUTI to {"public.item"}

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



repeat with itemFilePath in listFilePath
  set strFilePath to POSIX path of itemFilePath as text
  
  set ocidFilePathStr to (refMe's NSString's stringWithString:strFilePath)
  set ocidFilePath to ocidFilePathStr's stringByExpandingTildeInPath()
  ###
  set listResponse to (appFileManager's attributesOfItemAtPath:ocidFilePath |error|:(reference))
  set ocidAttarDict to item 1 of listResponse
  set ocidExtendAttr to (ocidAttarDict's valueForKey:"NSFileExtendedAttributes")
  #################################
  ####個別方式
  if ocidExtendAttr is not (missing value) then
    set listExtendAttr to ocidExtendAttr's allKeys() as list
    ###
    repeat with itemExtendAttr in listExtendAttr
      set strExtendAttr to itemExtendAttr as text
      set strCommandText to ("/usr/bin/xattr -rd " & strExtendAttr & "  \"" & strFilePath & "\"") as text
      ##do shell script strCommandText
      set ocidCommandText to (refMe's NSString's stringWithString:strCommandText)
      set ocidTermTask to refMe's NSTask's alloc()'s init()
      (ocidTermTask's setLaunchPath:"/bin/zsh")
      (ocidTermTask's setArguments:({"-c", ocidCommandText}))
      set listDoneReturn to (ocidTermTask's launchAndReturnError:(reference))
      if (item 2 of listDoneReturn) is not (missing value) then
        log "エラーコード:" & (item 2 of listDoneReturn)'s code() as text
        log "エラードメイン:" & (item 2 of listDoneReturn)'s domain() as text
        log "Description:" & (item 2 of listDoneReturn)'s localizedDescription() as text
        log "FailureReason:" & (item 2 of listDoneReturn)'s localizedFailureReason() as text
      end if
    end repeat
  end if
  ########################################
  ####まとめて削除方式
  ####コマンド整形
  set strCommandText to ("/usr/bin/xattr -rc  \"" & strFilePath & "\"") as text
  ##do shell script strCommandText
  set ocidCommandText to (refMe's NSString's stringWithString:strCommandText)
  set ocidTermTask to refMe's NSTask's alloc()'s init()
  (ocidTermTask's setLaunchPath:"/bin/zsh")
  (ocidTermTask's setArguments:({"-c", ocidCommandText}))
  set listDoneReturn to (ocidTermTask's launchAndReturnError:(reference))
  if (item 2 of listDoneReturn) is not (missing value) then
    log "エラーコード:" & (item 2 of listDoneReturn)'s code() as text
    log "エラードメイン:" & (item 2 of listDoneReturn)'s domain() as text
    log "Description:" & (item 2 of listDoneReturn)'s localizedDescription() as text
    log "FailureReason:" & (item 2 of listDoneReturn)'s localizedFailureReason() as text
  end if
  
  
end repeat



|

ファイルに設定されているNSFileExtendedAttributesを削除する

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

#!/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)
###ExtendedAttributesを分離取得
set ocidExtendedAttrDict to (ocidFileAttr's valueForKey:"NSFileExtendedAttributes")
###設定されているキーを取得
set ocidAllKyesArray to ocidExtendedAttrDict's allKeys()
###キーの数だけ繰り返し
repeat with itemAllKyesArray in ocidAllKyesArray
  ###削除する
  (ocidExtendedAttrDict's removeObjectForKey:itemAllKyesArray)
end repeat
###確認
if (ocidExtendedAttrDict's valueForKey:"NSFileExtendedAttributes") is missing value then
  log "全て削除しました"
else
  log "何か残ってます"
end if


|

その他のカテゴリー

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