Admin LaunchServices

[launchctl] 停止処理(v2 plistの値の変更)

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

launchctl停止.applescript
ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(* # サービスの停止 要管理者権限
004v1 初回作成
005v2 PLISTの値を停止にする処理も入れた(いっそ削除した方が早いような)
006
007キーの値はOBJCで取得して
008設定の変更はzshAppleScriptならでわの処理
009
010com.cocolog-nifty.quicktimer.icefloe *)
011----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
012use AppleScript version "2.8"
013use framework "Foundation"
014use framework "UniformTypeIdentifiers"
015use framework "AppKit"
016use scripting additions
017
018property refMe : a reference to current application
019
020###################################
021#####収集
022###################################
023set ocidURLArray to refMe's NSMutableArray's alloc()'s init()
024#
025set appFileManager to refMe's NSFileManager's defaultManager()
026set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSLocalDomainMask))
027set ocidLocalLibraryDirPathURL to ocidURLsArray's firstObject()
028set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSUserDomainMask))
029set ocidUseerLibraryDirPathURL to ocidURLsArray's firstObject()
030#
031set ocidLocalAgentsDirPathURL to ocidLocalLibraryDirPathURL's URLByAppendingPathComponent:("LaunchAgents") isDirectory:(true)
032set ocidLocalDaemonsDirPathURL to ocidLocalLibraryDirPathURL's URLByAppendingPathComponent:("LaunchDaemons") isDirectory:(true)
033set ocidUserAgentsDirPathURL to ocidUseerLibraryDirPathURL's URLByAppendingPathComponent:("LaunchAgents") isDirectory:(true)
034#
035set ocidHomeDirURL to appFileManager's homeDirectoryForCurrentUser()
036set strHomeDirURL to ocidHomeDirURL's |path|() as text
037#
038set ocidOption to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
039set ocidKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
040ocidKeyArray's addObject:(refMe's NSURLPathKey)
041ocidKeyArray's addObject:(refMe's NSURLNameKey)
042set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidLocalAgentsDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error|:(reference))
043set ocidSubPathURLArray to (item 1 of listResponse)
044ocidURLArray's addObjectsFromArray:(ocidSubPathURLArray)
045set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidLocalDaemonsDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error|:(reference))
046set ocidSubPathURLArray to (item 1 of listResponse)
047ocidURLArray's addObjectsFromArray:(ocidSubPathURLArray)
048set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidUserAgentsDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error|:(reference))
049set ocidSubPathURLArray to (item 1 of listResponse)
050ocidURLArray's addObjectsFromArray:(ocidSubPathURLArray)
051#ソートして
052set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("absoluteString") ascending:(yes) selector:("localizedStandardCompare:")
053set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
054set ocidURLSortArray to ocidURLArray's sortedArrayUsingDescriptors:(ocidDescriptorArray)
055#ダイアログ用にテキストのパスリストにする
056set listFilePath to {} as list
057repeat with itemURL in ocidURLSortArray
058   set strFilePath to itemURL's |path|() as text
059   set end of listFilePath to strFilePath
060end repeat
061###################################
062#####入力ダイアログ
063###################################
064set strName to (name of current application) as text
065if strName is "osascript" then
066   tell application "Finder" to activate
067else
068   tell current application to activate
069end if
070set strPrompt to "\r ファイルを選んでください\r launchctl unloadして停止します(再起動後も有効)\r \r " as text
071set strTitle to "ファイルを選んでください" as text
072try
073   set listResponse to (choose from list listFilePath with title strTitle with prompt strPrompt default items (item 1 of listFilePath) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed without empty selection allowed) as list
074on error
075   log "エラーしました"
076   return "エラーしました"
077   error "エラーしました" number -200
078end try
079if listResponse = {} then
080   log "何も選択していない"
081   # 止めるなら ここに returnを入れる
082else if (item 1 of listResponse) is false then
083   return "キャンセルしました"
084   error "キャンセルしました" number -200
085else
086   set listFilePath to listResponse as list
087end if
088###################################
089#####判定材料
090###################################
091#UID
092set recordSystemInfo to (system info) as record
093set strUID to (user ID of recordSystemInfo) as text
094set strSetUID to ("gui/" & strUID) as text
095
096###################################
097#####MachServices Falseにする
098###################################
099
100repeat with itemFilePath in listFilePath
101   set strFilePath to itemFilePath as text
102   log strFilePath
103   set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
104   set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
105   set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:(false))
106   #設定されているキー名称はOBJCで取得して
107   set listResponse to (refMe's NSDictionary's alloc()'s initWithContentsOfURL:(ocidFilePathURL) |error|:(reference))
108   set ocidPlistDict to (item 1 of listResponse)
109   set ocidMachServicesDict to (ocidPlistDict's objectForKey:("MachServices"))
110   if ocidMachServicesDict ≠ (missing value) then
111      set ocidAllKeys to ocidMachServicesDict's allKeys()
112      #コマンドはzshで実行
113      repeat with itemKey in ocidAllKeys
114         set strKey to itemKey as text
115         if strFilePath contains strHomeDirURL then
116            set strCommandText to ("/usr/libexec/PlistBuddy -c \"Set:MachServices:" & strKey & " false\" \"" & strFilePath & "\" ") as text
117            log doZshShellScript(strCommandText)
118            set strCommandText to ("/usr/libexec/PlistBuddy -c \"Save\" \"" & strFilePath & "\" ") as text
119            log doZshShellScript(strCommandText)
120         else
121            set strCommandText to ("/usr/libexec/PlistBuddy -c \"Set:MachServices:" & strKey & " false\" \"" & strFilePath & "\" ") as text
122            log doZshShellScriptSUDO(strCommandText)
123            set strCommandText to ("/usr/libexec/PlistBuddy -c \"Save\" \"" & strFilePath & "\" ") as text
124            log doZshShellScriptSUDO(strCommandText)
125         end if
126      end repeat
127   end if
128   set boolRunAtLoad to (ocidPlistDict's valueForKey:("RunAtLoad"))
129   if boolRunAtLoad ≠ (missing value) then
130      set boolRunAtLoad to boolRunAtLoad as boolean
131   end if
132   if boolRunAtLoad is true then
133      if strFilePath contains strHomeDirURL then
134         set strCommandText to ("/usr/libexec/PlistBuddy -c \"Set:RunAtLoad false\" \"" & strFilePath & "\" ") as text
135         log doZshShellScript(strCommandText)
136         set strCommandText to ("/usr/libexec/PlistBuddy -c \"Save\" \"" & strFilePath & "\" ") as text
137         log doZshShellScript(strCommandText)
138      else
139         set strCommandText to ("/usr/libexec/PlistBuddy -c \"Set:RunAtLoad false\" \"" & strFilePath & "\" ") as text
140         log doZshShellScriptSUDO(strCommandText)
141         set strCommandText to ("/usr/libexec/PlistBuddy -c \"Save\" \"" & strFilePath & "\" ") as text
142         log doZshShellScriptSUDO(strCommandText)
143      end if
144   end if
145   
146end repeat
147
148
149###################################
150#####本処理 disable
151###################################
152
153repeat with itemFilePath in listFilePath
154   set strFilePath to itemFilePath as text
155   set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
156   set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
157   set ocidFileName to ocidFilePath's lastPathComponent()
158   set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension()
159   set strBaseFileName to ocidBaseFileName as text
160   set strSetService to (strSetUID & "/" & strBaseFileName) as text
161   ##
162   if strFilePath contains strHomeDirURL then
163      set strCommandText to ("/bin/launchctl disable \"" & strSetService & "\"") as text
164      log doZshShellScript(strCommandText)
165   else
166      set strCommandText to ("/bin/launchctl disable \"" & strSetService & "\"") as text
167      log doZshShellScript(strCommandText)
168      set strSetSudoService to ("system/" & strBaseFileName) as text
169      set strCommandText to ("/bin/launchctl disable \"" & strSetSudoService & "\"") as text
170      log doZshShellScriptSUDO(strCommandText)
171   end if
172end repeat
173
174
175
176
177###################################
178#####本処理 unload
179###################################
180
181repeat with itemFilePath in listFilePath
182   set strFilePath to itemFilePath as text
183   ##
184   if strFilePath contains strHomeDirURL then
185      set strCommandText to ("/bin/launchctl unload -w \"" & strFilePath & "\"") as text
186      log doZshShellScript(strCommandText)
187   else
188      set strCommandText to ("/bin/launchctl unload -w \"" & strFilePath & "\"") as text
189      log doZshShellScript(strCommandText)
190      set strCommandText to ("/bin/launchctl unload -w \"" & strFilePath & "\"") as text
191      log doZshShellScriptSUDO(strCommandText)
192   end if
193   
194   
195end repeat
196
197
198
199###################################
200#####本処理 bootout
201###################################
202
203repeat with itemFilePath in listFilePath
204   set strFilePath to itemFilePath as text
205   set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
206   set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
207   set ocidFileName to ocidFilePath's lastPathComponent()
208   set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension()
209   set strBaseFileName to ocidBaseFileName as text
210   set strSetService to (strSetUID & "/" & strBaseFileName) as text
211   
212   ##
213   if strFilePath contains strHomeDirURL then
214      set strCommandText to ("/bin/launchctl bootout \"" & strSetService & "\"") as text
215      log doZshShellScript(strCommandText)
216   else
217      set strCommandText to ("/bin/launchctl bootout \"" & strSetService & "\"") as text
218      log doZshShellScript(strCommandText)
219      #SUDO
220      set strSetSudoService to ("system/" & strBaseFileName) as text
221      set strCommandText to ("/bin/launchctl bootout \"" & strSetSudoService & "\"") as text
222      log doZshShellScriptSUDO(strCommandText)
223      
224   end if
225end repeat
226
227
228##########################
229# 【通常】ZSH 実行
230to doZshShellScript(argCommandText)
231   set strCommandText to argCommandText as text
232   log "\r" & strCommandText & "\r"
233   set strExec to ("/bin/zsh -c '" & strCommandText & "'") as text
234   log "\r" & strExec & "\r"
235   ##########
236   #コマンド実行
237   try
238      log "コマンド開始"
239      set strResnponse to (do shell script strExec) as text
240      log "コマンド終了"
241   on error
242      return false
243   end try
244   return strResnponse
245end doZshShellScript
246
247
248
249##########################
250# SUDOZSH 実行
251to doZshShellScriptSUDO(argCommandText)
252   set strCommandText to argCommandText as text
253   log "\r" & strCommandText & "\r"
254   set strExec to ("/bin/zsh -c '/usr/bin/sudo " & strCommandText & "'") as text
255   log "\r" & strExec & "\r"
256   ##########
257   #コマンド実行
258   try
259      log "コマンド開始"
260      set strResnponse to (do shell script strExec) as text
261      log "コマンド終了"
262   on error
263      return false
264   end try
265   return strResnponse
266end doZshShellScriptSUDO
AppleScriptで生成しました

| | コメント (0)

[ユーティリティ]Startup Folder 起動時に実行するアプリをカスタマイズできるアプリ

LaunchAgentsの設定を書かなくても
『Keep alive』設定ができる
要はうっかり終了してしまっても監視しているので
再度勝手に再度起動してくれる

『Hide on launch』隠して起動もサポートしているので
FontBookには最適解かもしれない
202502071230081_1584x566


何か?理由がありそうだけど
初期設定の場所がユーザールートになっているので
そこだけは変更した方がいいだろう

202502071236391_1206x444

https://lowtechguys.com/startupfolder/



|

[launchctl]ローカルドメイン・ユーザドメインで選択したサービスを停止させる(少し修正)


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# サービスの停止 要管理者権限
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "UniformTypeIdentifiers"
009use framework "AppKit"
010use scripting additions
011
012property refMe : a reference to current application
013
014###################################
015#####収集
016###################################
017set ocidURLArray to refMe's NSMutableArray's alloc()'s init()
018#
019set appFileManager to refMe's NSFileManager's defaultManager()
020set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSLocalDomainMask))
021set ocidLocalLibraryDirPathURL to ocidURLsArray's firstObject()
022set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSUserDomainMask))
023set ocidUseerLibraryDirPathURL to ocidURLsArray's firstObject()
024#
025set ocidLocalAgentsDirPathURL to ocidLocalLibraryDirPathURL's URLByAppendingPathComponent:("LaunchAgents") isDirectory:(true)
026set ocidLocalDaemonsDirPathURL to ocidLocalLibraryDirPathURL's URLByAppendingPathComponent:("LaunchDaemons") isDirectory:(true)
027set ocidUserAgentsDirPathURL to ocidUseerLibraryDirPathURL's URLByAppendingPathComponent:("LaunchAgents") isDirectory:(true)
028#
029set ocidHomeDirURL to appFileManager's homeDirectoryForCurrentUser()
030set strHomeDirURL to ocidHomeDirURL's |path|() as text
031#
032set ocidOption to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
033set ocidKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
034ocidKeyArray's addObject:(refMe's NSURLPathKey)
035ocidKeyArray's addObject:(refMe's NSURLNameKey)
036set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidLocalAgentsDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error| :(reference))
037set ocidSubPathURLArray to (item 1 of listResponse)
038ocidURLArray's addObjectsFromArray:(ocidSubPathURLArray)
039set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidLocalDaemonsDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error| :(reference))
040set ocidSubPathURLArray to (item 1 of listResponse)
041ocidURLArray's addObjectsFromArray:(ocidSubPathURLArray)
042set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidUserAgentsDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error| :(reference))
043set ocidSubPathURLArray to (item 1 of listResponse)
044ocidURLArray's addObjectsFromArray:(ocidSubPathURLArray)
045#ソートして
046set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("absoluteString") ascending:(yes) selector:("localizedStandardCompare:")
047set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
048set ocidURLSortArray to ocidURLArray's sortedArrayUsingDescriptors:(ocidDescriptorArray)
049#ダイアログ用にテキストのパスリストにする
050set listFilePath to {} as list
051repeat with itemURL in ocidURLSortArray
052  set strFilePath to itemURL's |path|() as text
053  set end of listFilePath to strFilePath
054end repeat
055###################################
056#####入力ダイアログ
057###################################
058set strName to (name of current application) as text
059if strName is "osascript" then
060  tell application "Finder" to activate
061else
062  tell current application to activate
063end if
064set strPrompt to "\r ファイルを選んでください\r launchctl unloadして停止します(再起動後も有効)\r \r " as text
065set strTitle to "ファイルを選んでください" as text
066try
067  set listResponse to (choose from list listFilePath with title strTitle with prompt strPrompt default items (item 1 of listFilePath) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed without empty selection allowed) as list
068on error
069  log "エラーしました"
070  return "エラーしました"
071  error "エラーしました" number -200
072end try
073if listResponse = {} then
074  log "何も選択していない"
075  # 止めるなら ここに returnを入れる
076else if (item 1 of listResponse) is false then
077  return "キャンセルしました"
078  error "キャンセルしました" number -200
079else
080  set listFilePath to listResponse as list
081end if
082###################################
083#####判定材料
084###################################
085#UID
086set recordSystemInfo to (system info) as record
087set strUID to (user ID of recordSystemInfo) as text
088set strSetUID to ("gui/" & strUID) as text
089
090
091###################################
092#####本処理 disable
093###################################
094
095repeat with itemFilePath in listFilePath
096  set strFilePath to itemFilePath as text
097  set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
098  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
099  set ocidFileName to ocidFilePath's lastPathComponent()
100  set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension()
101  set strBaseFileName to ocidBaseFileName as text
102  set strSetService to (strSetUID & "/" & strBaseFileName) as text
103  ##
104  if strFilePath contains strHomeDirURL then
105    set strCommandText to ("/bin/launchctl disable  \"" & strSetService & "\"") as text
106  else
107    set strCommandText to ("/usr/bin/sudo /bin/launchctl disable  \"" & strSetService & "\"") as text
108  end if
109  log "\r" & strCommandText & "\r"
110  set strExec to ("/bin/zsh -c '" & strCommandText & "'") as text
111  try
112    do shell script strExec
113  on error
114    log strFilePath & "エラーしました"
115    set strCommandText to ("/usr/bin/sudo /bin/launchctl disable \"" & strSetService & "\"") as text
116    log "\r" & strCommandText & "\r"
117    set strExec to ("/bin/zsh -c '" & strCommandText & "'") as text
118    try
119      do shell script strExec
120    end try
121  end try
122end repeat
123
124
125
126
127###################################
128#####本処理 unload
129###################################
130
131repeat with itemFilePath in listFilePath
132  set strFilePath to itemFilePath as text
133  ##
134  if strFilePath contains strHomeDirURL then
135    set strCommandText to ("/bin/launchctl unload -w  \"" & strFilePath & "\"") as text
136  else
137    set strCommandText to ("/usr/bin/sudo /bin/launchctl unload -w  \"" & strFilePath & "\"") as text
138  end if
139  log "\r" & strCommandText & "\r"
140  set strExec to ("/bin/zsh -c '" & strCommandText & "'") as text
141  try
142    do shell script strExec
143  on error
144    log strFilePath & "エラーしました"
145    set strCommandText to ("/usr/bin/sudo /bin/launchctl unload -w  \"" & strFilePath & "\"") as text
146    log "\r" & strCommandText & "\r"
147    set strExec to ("/bin/zsh -c '" & strCommandText & "'") as text
148    try
149      do shell script strExec
150    end try
151  end try
152end repeat
153
154
155
156###################################
157#####本処理 bootout
158###################################
159
160repeat with itemFilePath in listFilePath
161  set strFilePath to itemFilePath as text
162  ##
163  if strFilePath contains strHomeDirURL then
164    set strCommandText to ("/bin/launchctl bootout " & strSetUID & " \"" & strFilePath & "\"") as text
165  else
166    set strCommandText to ("/usr/bin/sudo /bin/launchctl bootout " & strSetUID & " \"" & strFilePath & "\"") as text
167  end if
168  log "\r" & strCommandText & "\r"
169  set strExec to ("/bin/zsh -c '" & strCommandText & "'") as text
170  try
171    do shell script strExec
172  on error
173    log strFilePath & "エラーしました"
174    set strCommandText to ("/usr/bin/sudo /bin/launchctl bootout " & strSetUID & " \"" & strFilePath & "\"") as text
175    log "\r" & strCommandText & "\r"
176    set strExec to ("/bin/zsh -c '" & strCommandText & "'") as text
177    try
178      do shell script strExec
179    end try
180  end try
181  
182end repeat
183
AppleScriptで生成しました

|

[launchctl]ファイルを選択して再開


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# サービスの停止 要管理者権限
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "UniformTypeIdentifiers"
009use framework "AppKit"
010use scripting additions
011
012property refMe : a reference to current application
013
014###################################
015#####収集
016###################################
017set ocidURLArray to refMe's NSMutableArray's alloc()'s init()
018#
019set appFileManager to refMe's NSFileManager's defaultManager()
020set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSLocalDomainMask))
021set ocidLocalLibraryDirPathURL to ocidURLsArray's firstObject()
022set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSUserDomainMask))
023set ocidUseerLibraryDirPathURL to ocidURLsArray's firstObject()
024#
025set ocidLocalAgentsDirPathURL to ocidLocalLibraryDirPathURL's URLByAppendingPathComponent:("LaunchAgents") isDirectory:(true)
026set ocidLocalDaemonsDirPathURL to ocidLocalLibraryDirPathURL's URLByAppendingPathComponent:("LaunchDaemons") isDirectory:(true)
027set ocidUserAgentsDirPathURL to ocidUseerLibraryDirPathURL's URLByAppendingPathComponent:("LaunchAgents") isDirectory:(true)
028#
029set ocidHomeDirURL to appFileManager's homeDirectoryForCurrentUser()
030set strHomeDirURL to ocidHomeDirURL's |path|() as text
031#
032set ocidOption to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
033set ocidKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
034ocidKeyArray's addObject:(refMe's NSURLPathKey)
035ocidKeyArray's addObject:(refMe's NSURLNameKey)
036set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidLocalAgentsDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error| :(reference))
037set ocidSubPathURLArray to (item 1 of listResponse)
038ocidURLArray's addObjectsFromArray:(ocidSubPathURLArray)
039set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidLocalDaemonsDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error| :(reference))
040set ocidSubPathURLArray to (item 1 of listResponse)
041ocidURLArray's addObjectsFromArray:(ocidSubPathURLArray)
042set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidUserAgentsDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error| :(reference))
043set ocidSubPathURLArray to (item 1 of listResponse)
044ocidURLArray's addObjectsFromArray:(ocidSubPathURLArray)
045#ソートして
046set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("absoluteString") ascending:(yes) selector:("localizedStandardCompare:")
047set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
048set ocidURLSortArray to ocidURLArray's sortedArrayUsingDescriptors:(ocidDescriptorArray)
049#ダイアログ用にテキストのパスリストにする
050set listFilePath to {} as list
051repeat with itemURL in ocidURLSortArray
052  set strFilePath to itemURL's |path|() as text
053  set end of listFilePath to strFilePath
054end repeat
055###################################
056#####入力ダイアログ
057###################################
058set strName to (name of current application) as text
059if strName is "osascript" then
060  tell application "Finder" to activate
061else
062  tell current application to activate
063end if
064set strPrompt to "\r ファイルを選んでください\r launchctl unloadして停止します(再起動後も有効)\r \r " as text
065set strTitle to "ファイルを選んでください" as text
066try
067  set listResponse to (choose from list listFilePath with title strTitle with prompt strPrompt default items (item 1 of listFilePath) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed without empty selection allowed) as list
068on error
069  log "エラーしました"
070  return "エラーしました"
071  error "エラーしました" number -200
072end try
073if listResponse = {} then
074  log "何も選択していない"
075  # 止めるなら ここに returnを入れる
076else if (item 1 of listResponse) is false then
077  return "キャンセルしました"
078  error "キャンセルしました" number -200
079else
080  set listFilePath to listResponse as list
081end if
082
083#####
084
085repeat with itemFilePath in listFilePath
086  set strFilePath to itemFilePath as text
087  ##
088  if strFilePath contains strHomeDirURL then
089    set strCommandText to ("/bin/launchctl load -w  \"" & strFilePath & "\"") as text
090  else
091    set strCommandText to ("/usr/bin/sudo /bin/launchctl load -w  \"" & strFilePath & "\"") as text
092  end if
093  log "\r" & strCommandText & "\r"
094  set strExec to ("/bin/zsh -c '" & strCommandText & "'") as text
095  try
096    do shell script strExec
097  on error
098    log strFilePath & "エラーしました"
099  end try
100  
101end repeat
AppleScriptで生成しました

|

[launchctl]ファイルを選択して停止


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# サービスの停止 要管理者権限
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "UniformTypeIdentifiers"
009use framework "AppKit"
010use scripting additions
011
012property refMe : a reference to current application
013
014###################################
015#####収集
016###################################
017set ocidURLArray to refMe's NSMutableArray's alloc()'s init()
018#
019set appFileManager to refMe's NSFileManager's defaultManager()
020set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSLocalDomainMask))
021set ocidLocalLibraryDirPathURL to ocidURLsArray's firstObject()
022set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSUserDomainMask))
023set ocidUseerLibraryDirPathURL to ocidURLsArray's firstObject()
024#
025set ocidLocalAgentsDirPathURL to ocidLocalLibraryDirPathURL's URLByAppendingPathComponent:("LaunchAgents") isDirectory:(true)
026set ocidLocalDaemonsDirPathURL to ocidLocalLibraryDirPathURL's URLByAppendingPathComponent:("LaunchDaemons") isDirectory:(true)
027set ocidUserAgentsDirPathURL to ocidUseerLibraryDirPathURL's URLByAppendingPathComponent:("LaunchAgents") isDirectory:(true)
028#
029set ocidHomeDirURL to appFileManager's homeDirectoryForCurrentUser()
030set strHomeDirURL to ocidHomeDirURL's |path|() as text
031#
032set ocidOption to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
033set ocidKeyArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
034ocidKeyArray's addObject:(refMe's NSURLPathKey)
035ocidKeyArray's addObject:(refMe's NSURLNameKey)
036set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidLocalAgentsDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error| :(reference))
037set ocidSubPathURLArray to (item 1 of listResponse)
038ocidURLArray's addObjectsFromArray:(ocidSubPathURLArray)
039set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidLocalDaemonsDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error| :(reference))
040set ocidSubPathURLArray to (item 1 of listResponse)
041ocidURLArray's addObjectsFromArray:(ocidSubPathURLArray)
042set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidUserAgentsDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error| :(reference))
043set ocidSubPathURLArray to (item 1 of listResponse)
044ocidURLArray's addObjectsFromArray:(ocidSubPathURLArray)
045#ソートして
046set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("absoluteString") ascending:(yes) selector:("localizedStandardCompare:")
047set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
048set ocidURLSortArray to ocidURLArray's sortedArrayUsingDescriptors:(ocidDescriptorArray)
049#ダイアログ用にテキストのパスリストにする
050set listFilePath to {} as list
051repeat with itemURL in ocidURLSortArray
052  set strFilePath to itemURL's |path|() as text
053  set end of listFilePath to strFilePath
054end repeat
055###################################
056#####入力ダイアログ
057###################################
058set strName to (name of current application) as text
059if strName is "osascript" then
060  tell application "Finder" to activate
061else
062  tell current application to activate
063end if
064set strPrompt to "\r ファイルを選んでください\r launchctl unloadして停止します(再起動後も有効)\r \r " as text
065set strTitle to "ファイルを選んでください" as text
066try
067  set listResponse to (choose from list listFilePath with title strTitle with prompt strPrompt default items (item 1 of listFilePath) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed without empty selection allowed) as list
068on error
069  log "エラーしました"
070  return "エラーしました"
071  error "エラーしました" number -200
072end try
073if listResponse = {} then
074  log "何も選択していない"
075  # 止めるなら ここに returnを入れる
076else if (item 1 of listResponse) is false then
077  return "キャンセルしました"
078  error "キャンセルしました" number -200
079else
080  set listFilePath to listResponse as list
081end if
082
083#####
084
085repeat with itemFilePath in listFilePath
086  set strFilePath to itemFilePath as text
087  ##
088  if strFilePath contains strHomeDirURL then
089    set strCommandText to ("/bin/launchctl unload -w  \"" & strFilePath & "\"") as text
090  else
091    set strCommandText to ("/usr/bin/sudo /bin/launchctl unload -w  \"" & strFilePath & "\"") as text
092  end if
093  log "\r" & strCommandText & "\r"
094  set strExec to ("/bin/zsh -c '" & strCommandText & "'") as text
095  try
096    do shell script strExec
097  on error
098    log strFilePath & "エラーしました"
099  end try
100  
101end repeat
AppleScriptで生成しました

|

[lsregister]ファイルの関連付けのリセット(ユーザー権限で可能な範囲)

1:ソフトな方法
2:コマンドで実行する方法

1:ソフトな方法
1:全てのアプリケーションを終了させる

2:com.apple.LaunchServicesを移動
/Users/ユーザーID/Library/Preferences/com.apple.LaunchServices

フォルダをデスクトップに移動してください

3:デバイスを電源OFFシステム終了してからの(再起動じゃないよ) 電源ON

電源ON後は15分ほど高負荷状態になります(アプリケーションをスキャンするから)
問題なければ

デスクトップに移動したcom.apple.LaunchServicesフォルダは削除しても大丈夫です


2:コマンドで実行する方法

サンプルコード

サンプルソース(参考)
行番号ソース
001#!/bin/bash
002#com.cocolog-nifty.quicktimer.icefloe
003#UID取得
004STAT_USR=$(/usr/bin/stat -f%Su /dev/console)
005/bin/echo "STAT_USR(console): $STAT_USR"
006
007/bin/sync
008/bin/sync
009/usr/sbin/purge
010
011/usr/bin/defaults delete com.apple.LaunchServices
012/bin/mv "/Users/${STAT_USR}/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2" "/Users/${STAT_USR}/.Trash"
013/bin/mv "/Users/${STAT_USR}/Library/Preferences/com.apple.LaunchServices" "/Users/${STAT_USR}/.Trash"
014#ターミナルにペーストしたい場合は
015: << 'COMMENT'
016/bin/mv "${HOME}/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2" "${HOME}/.Trash"
017/bin/mv "${HOME}/Library/Preferences/com.apple.LaunchServices" "${HOME}/.Trash"
018COMMENT
019
020#単純にリビルドする場合
021#ユーザー環境のみが対象 状況表示
022/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -lint
023
024#アプリケーションのみ(ユーザーが追加した分)
025/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -seed /Applications -apps user
026
027#アプリケーションのみ(全部)
028/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -seed / -apps user
029
030#ライブラリも参照リビルド
031/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -seed / -libs user
032
033#全てリビルド
034/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -seed / -all user
035
036/bin/echo "必ず再起動(システム終了後に電源ON)を実施すること"
037exit 0
AppleScriptで生成しました

|

Macでファイルを開くアプリを選択する(ファイルをデフォルトで開くアプリを設定・変更する)



ダウンロード - setdefaults.zip




ダイアログに
ファイルをドラッグ&ドロップでもOK

Photo_20241103140702Photo_20241103140701
AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# ファイルタイプのデフォルトのアプリケーションを変更します
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "UniformTypeIdentifiers"
009use framework "AppKit"
010use scripting additions
011property refMe : a reference to current application
012
013
014set strMes to ("ファイルの拡張子を入力\n入力欄に対象ファイルのドロップでもOK") as text
015
016
017##############################
018#####ダイアログ
019##############################
020###ダイアログを前面に出す
021set strName to (name of current application) as text
022if strName is "osascript" then
023  tell application "Finder" to activate
024else
025  tell current application to activate
026end if
027set aliasIconPath to POSIX file "/System/Library/CoreServices/Finder.app/Contents/Resources/Finder.icns" as alias
028try
029  set recordResult to (display dialog strMes with title "ファイルタイプのデフォルトのアプリケーションを変更します" default answer "" buttons {"OK", "キャンセル"} default button "OK" with icon aliasIconPath giving up after 20 without hidden answer) as record
030on error
031  log "エラーしました"
032  return
033end try
034if "OK" is equal to (button returned of recordResult) then
035  set strReturnedText to (text returned of recordResult) as text
036else if (gave up of recordResult) is true then
037  return "時間切れです"
038else
039  return "キャンセル"
040end if
041##############################
042#####戻り値整形
043##############################
044set ocidResponseText to (refMe's NSString's stringWithString:(strReturnedText))
045###タブと改行を除去しておく
046set ocidResponseText to (ocidResponseText's stringByReplacingOccurrencesOfString:("\n") withString:(""))
047set ocidResponseText to (ocidResponseText's stringByReplacingOccurrencesOfString:("\r") withString:(""))
048##############################
049#####パスドロップの場合
050##############################
051if (ocidResponseText as text) contains "/" then
052  set ocidFilePathStr to refMe's NSString's stringWithString:(ocidResponseText)
053  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
054  set ocidResponseText to ocidFilePath's pathExtension()
055end if
056#カンマ取る
057set ocidResponseText to (ocidResponseText's stringByReplacingOccurrencesOfString:(".") withString:(""))
058
059##############################
060#####処理
061##############################
062set ocidExtensionTType to refMe's UTType's typeWithFilenameExtension:(ocidResponseText)
063set ocitExtensionUTI to ocidExtensionTType's identifier()
064
065###ワークスペース初期化
066set appShardWorkspace to refMe's NSWorkspace's sharedWorkspace()
067###UTTypeタイプのデフォルトアプリケーション
068set ocidAppPathURL to appShardWorkspace's URLsForApplicationsToOpenContentType:(ocidExtensionTType)
069
070################################################
071###起動ボリュームにあるURLのみにする
072###URL格納用の可変ARRAY
073set ocidChooseArray to refMe's NSMutableArray's alloc()'s initWithCapacity:0
074ocidChooseArray's setArray:ocidAppPathURL
075###収集したURLの個数
076set numCntArray to count of ocidAppPathURL
077###収集したURLから外部ボリュームのものを削除
078###起動ボリュームの名前
079set strFilePath to "/System/Library/CoreServices/Finder.app" as text
080set ocidFinderFilePathStr to refMe's NSString's stringWithString:(strFilePath)
081set ocidFinderFilePath to ocidFinderFilePathStr's stringByStandardizingPath()
082set ocidFinderFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFinderFilePath) isDirectory:false)
083set listVolumeNameKey to (ocidFinderFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLVolumeNameKey) |error| :(reference))
084set strVolumeName to (item 2 of listVolumeNameKey) as text
085####収集したURLの数だけ繰り返し
086repeat numCntArray times
087  ###Arrayの削除なので後ろから処理
088  set itemAppPathURL to ocidChooseArray's objectAtIndex:(numCntArray - 1)
089  ###ボリューム名を取得して
090  set listPathVolumeName to (itemAppPathURL's getResourceValue:(reference) forKey:(refMe's NSURLVolumeNameKey) |error| :(reference))
091  set strPathVolumeName to (item 2 of listPathVolumeName) as text
092  ###外部ボリュームのものは削除
093  if strPathVolumeName is "Preboot" then
094    log strPathVolumeName
095  else if strPathVolumeName is not strVolumeName then
096    ocidChooseArray's removeObjectAtIndex:(numCntArray - 1)
097  end if
098  set numCntArray to numCntArray - 1
099end repeat
100
101
102################################################
103###アプリ名とURLのレコードを生成する
104###ダイアログ用のアプリケーション名リスト
105set listAppName to {} as list
106###アプリケーションのURLを参照させるためのレコード
107set ocidBrowserDictionary to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
108####################################################
109####UTTypeとして利用可能なアプリケーション一覧を取得する
110####################################################
111repeat with itemAppPathURL in ocidChooseArray
112  ###アプリケーションの名前
113  set listResponse to (itemAppPathURL's getResourceValue:(reference) forKey:(refMe's NSURLNameKey) |error| :(missing value))
114  set strAppName to (item 2 of listResponse) as text
115  log "ブラウザの名前は:" & strAppName & "です"
116  copy strAppName to end of listAppName
117  ####パス
118  set aliasAppPath to itemAppPathURL's absoluteURL() as alias
119  log "ブラウザのパスは:" & aliasAppPath & "です"
120  ####バンドルID取得
121  set ocidAppBunndle to (refMe's NSBundle's bundleWithURL:(itemAppPathURL))
122  set ocidBunndleID to ocidAppBunndle's bundleIdentifier
123  set strBundleID to ocidBunndleID as text
124  log "ブラウザのBunndleIDは:" & strBundleID & "です"
125  (ocidBrowserDictionary's setObject:(itemAppPathURL) forKey:(strAppName))
126end repeat
127################################
128#ソート
129set ocidAppNameArray to refMe's NSArray's arrayWithArray:(listAppName)
130set ocidSortedArray to ocidAppNameArray's sortedArrayUsingSelector:("localizedStandardCompare:")
131set listAppName to ocidSortedArray as list
132
133################################
134##ダイアログ
135################################
136###ダイアログを前面に
137tell current application
138  set strName to name as text
139end tell
140####スクリプトメニューから実行したら
141if strName is "osascript" then
142  tell application "Finder"
143    activate
144  end tell
145else
146  tell current application
147    activate
148  end tell
149end if
150set strPrompt to ("拡張子『" & ocidResponseText & "』をURLを開く\nデフォルトアプリケーションを選んでください") as text
151try
152  set listResponse to (choose from list listAppName with title "選んでください" with prompt strPrompt default items (item 1 of listAppName) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed)
153on error
154  log "エラーしました"
155  return "エラーしました"
156end try
157if listResponse is false then
158  return "キャンセルしました"
159end if
160set strResponse to (item 1 of listResponse) as text
161################################
162##アプリケーションのURLを取得する
163################################
164###アプリケーションのURLを取り出す
165set ocidAppPathURL to ocidBrowserDictionary's objectForKey:(strResponse)
166###選んだアプリケーションのバンドルID
167set ocidAppBunndle to (refMe's NSBundle's bundleWithURL:(ocidAppPathURL))
168set ocidBunndleID to ocidAppBunndle's bundleIdentifier
169###IF用にテキストにしておく
170set strBunndleID to ocidBunndleID as text
171
172
173################################
174##デフォルトに設定する
175################################
176set appShardWorkspace to refMe's NSWorkspace's sharedWorkspace()
177appShardWorkspace's setDefaultApplicationAtURL:(ocidAppPathURL) toOpenContentType:(ocidExtensionTType) completionHandler:(missing value)
178
179
180################################
181##設定後に 値の確定
182################################
183
184set strFilePath to "~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"
185set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
186set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
187set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
188### PLISTを読み込む
189set ocidPlistDict to refMe's NSMutableDictionary's alloc()'s initWithContentsOfURL:(ocidFilePathURL)
190###LSHandlers Array
191set ocidLSHandlersArray to ocidPlistDict's objectForKey:"LSHandlers"
192###項目数の数だけ繰り返し
193repeat with itemLSHandlers in ocidLSHandlersArray
194  ###コンテンツタイプを取得して
195  set ocidLSHandlerContentType to (itemLSHandlers's valueForKey:"LSHandlerContentType")
196  ###設定項目のコンテンツタイプと同じなら
197  set strLSHandlerContentType to ocidLSHandlerContentType as text
198  if strLSHandlerContentType is ocitExtensionUTI then
199    ###変更前の値
200    set ocidRoleViewer to (itemLSHandlers's valueForKey:"LSHandlerRoleViewer")
201    set ocidRoleAll to (itemLSHandlers's valueForKey:"LSHandlerRoleAll")
202    set ocidRoleAll to (itemLSHandlers's valueForKey:"LSHandlerRoleEditor")
203    set ocidRoleShell to (itemLSHandlers's valueForKey:"LSHandlerRoleShell")
204    log ocidRoleViewer as text
205    log ocidRoleAll as text
206    log ocidRoleAll as text
207    log ocidRoleShell as text
208    ####値を変更する
209    (itemLSHandlers's setValue:(strBunndleID) forKey:"LSHandlerRoleViewer")
210    (itemLSHandlers's setValue:(strBunndleID) forKey:"LSHandlerRoleAll")
211    (itemLSHandlers's setValue:(strBunndleID) forKey:"LSHandlerRoleEditor")
212    (itemLSHandlers's setValue:(strBunndleID) forKey:"LSHandlerRoleShell")
213    ####変更後の値
214    log (itemLSHandlers's valueForKey:"LSHandlerRoleViewer") as text
215    log (itemLSHandlers's valueForKey:"LSHandlerRoleAll") as text
216    log (itemLSHandlers's valueForKey:"LSHandlerRoleEditor") as text
217    log (itemLSHandlers's valueForKey:"LSHandlerRoleShell") as text
218  end if
219  
220end repeat
221###保存
222set boolDone to ocidPlistDict's writeToURL:(ocidFilePathURL) atomically:true
223log boolDone as boolean
224
225
226#############################
227###CFPreferencesを再起動
228#############################
229#####CFPreferencesを再起動させて変更後の値をロードさせる
230set strCommandText to "/usr/bin/killall cfprefsd" as text
231do shell script strCommandText
232
233
234#############################
235###LaunchServicesを再起動
236#############################
237####lsregister初期化
238(*#色々やってみたが不具合の方が多いので停止
239set strCommandText to "/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -kill -seed" as text
240do shell script strCommandText
241*)
242
243
244log "設定終了"
245return "設定終了"
AppleScriptで生成しました

|

launchctlのplistファイルを0バイト(空)にしてロックする

ダウンロード - 0バイトロック.zip

|

[bash]lsregisterに不具合が発生した場合のリセット

202406100845281430x94022
サンプルコード

サンプルソース(参考)
行番号ソース
001#!/bin/bash
002#com.cocolog-nifty.quicktimer.icefloe
003#################################################
004###管理者インストールしているか?チェック
005USER_WHOAMI=$(/usr/bin/whoami)
006/bin/echo "実行ユーザー(whoami): $USER_WHOAMI"
007if [ "$USER_WHOAMI" != "root" ]; then
008  /bin/echo "このスクリプトを実行するには管理者権限が必要です。"
009  /bin/echo "sudo で実行してください"
010  ### path to me
011  SCRIPT_PATH="${BASH_SOURCE[0]}"
012  /bin/echo "/usr/bin/sudo \"$SCRIPT_PATH\""
013  /bin/echo "↑を実行してください"
014  exit 1
015else
016  ###実行しているユーザー名
017  CONSOLE_USER=$(/bin/echo "show State:/Users/ConsoleUser" | /usr/sbin/scutil | /usr/bin/awk '/Name :/ { print $3 }')
018  /bin/echo "コンソールユーザー(scutil): $CONSOLE_USER"
019  ###実行しているユーザー名
020  HOME_USER=$(/bin/echo "$HOME" | /usr/bin/awk -F'/' '{print $NF}')
021  /bin/echo "実行ユーザー(HOME): $HOME_USER"
022  ###logname
023  LOGIN_NAME=$(/usr/bin/logname)
024  /bin/echo "ログイン名(logname): $LOGIN_NAME"
025  ###UID
026  USER_NAME=$(/usr/bin/id -un)
027  /bin/echo "ユーザー名(id): $USER_NAME"
028  ###STAT
029  STAT_USR=$(/usr/bin/stat -f%Su /dev/console)
030  /bin/echo "STAT_USR(console): $STAT_USR"
031fi
032
033########################################
034##"system", "local", "network" "user"
035/bin/echo "チェック開始"
036STR_CMD_PATH="/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister"
037#書き出し先フォルダを作っておいて
038STR_SAVE_DIR_PATH="/Users/${STAT_USR}/Documents/Apple/Lsregister"
039/usr/bin/sudo -u "$STAT_USR" /bin/mkdir -p "$STR_SAVE_DIR_PATH"
040/usr/bin/sudo -u "$STAT_USR" /usr/bin/touch "$STR_SAVE_DIR_PATH/_このフォルダは削除しても大丈夫です.txt"
041STR_DATE_NO=$(/bin/date "+%m%d%H%M%Y")
042#チェック
043"$STR_CMD_PATH" -lint
044#ダンプします
045STR_SAVE_FILE_NAME="$STR_DATE_NO""_all.txt"
046STR_SAVE_FILE_PATH="${STR_SAVE_DIR_PATH}/${STR_SAVE_FILE_NAME}"
047"$STR_CMD_PATH" -dump | /usr/bin/sudo -u "$STAT_USR" tee -a "$STR_SAVE_FILE_PATH" >/dev/null
048#UTIを抽出
049STR_EXP_FILE_NAME="$STR_DATE_NO""_UTI.txt"
050STR_EXP_FILE_PATH="${STR_SAVE_DIR_PATH}/${STR_EXP_FILE_NAME}"
051/usr/bin/grep '^type id' "$STR_SAVE_FILE_PATH" | /usr/bin/sudo -u "$STAT_USR" tee -a "$STR_EXP_FILE_PATH" >/dev/null
052#名前とパスを抽出
053STR_EXP_FILE_NAME="$STR_DATE_NO""_NAME.txt"
054STR_EXP_FILE_PATH="${STR_SAVE_DIR_PATH}/${STR_EXP_FILE_NAME}"
055/usr/bin/grep -E "path:|name: | more" "$STR_SAVE_FILE_PATH" | /usr/bin/sudo -u "$STAT_USR" tee -a "$STR_EXP_FILE_PATH" >/dev/null
056#
057/bin/echo "再構築を実行しますか?"
058/bin/echo "Yを選択すると再起動します"
059/bin/echo "未保存の書類がある場合はNを入力してください"
060/bin/echo "Nを選択するとこのまま処理を終了します"
061/bin/echo "(Y/N)"
062
063read -r STR_USER_ANS
064# 入力に基づいて処理を分岐
065if [[ "$STR_USER_ANS" =~ ^[Yy]$ ]]; then
066  /bin/echo "lsregisterを削除してリセットします"
067  /bin/sync
068  sleep 1
069  /bin/sync
070  sleep 1
071  /usr/sbin/purge
072  sleep 1
073  "$STR_CMD_PATH" -delete
074  "$STR_CMD_PATH" -kill
075  /sbin/shutdown -r now
076elif [[ "$STR_USER_ANS" =~ ^[Nn]$ ]]; then
077  /bin/echo "処理を終了しますa"
078  exit 0
079else
080  /bin/echo "処理を終了しますb"
081  exit 1
082fi
AppleScriptで生成しました

|

[mobileconfig]ファイルの関連付けをデフォルトのプロファイルインストーラに戻す


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

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

###設定項目 ファイルタイプUTI
set strUTI to "com.apple.mobileconfig" as text

###UTTypに変換
set ocidUTType to refMe's UTType's typeWithIdentifier:(strUTI)
###ワークスペース初期化
set appShardWorkspace to refMe's NSWorkspace's sharedWorkspace()
###UTTypeタイプのデフォルトアプリケーション
set ocidAppPathURL to appShardWorkspace's URLsForApplicationsToOpenContentType:(ocidUTType)

################################################
###起動ボリュームにあるURLのみにする
###URL格納用の可変ARRAY
set ocidChooseArray to refMe's NSMutableArray's alloc()'s initWithCapacity:0
ocidChooseArray's setArray:ocidAppPathURL
###収集したURLの個数
set numCntArray to count of ocidAppPathURL
###収集したURLから外部ボリュームのものを削除
###起動ボリュームの名前
set strFilePath to "/System/Library/CoreServices/Finder.app" as text
set ocidFinderFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFinderFilePath to ocidFinderFilePathStr's stringByStandardizingPath()
set ocidFinderFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFinderFilePath) isDirectory:false)
set listVolumeNameKey to (ocidFinderFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLVolumeNameKey) |error|:(reference))
set strVolumeName to (item 2 of listVolumeNameKey) as text
####収集したURLの数だけ繰り返し
repeat numCntArray times
  ###Arrayの削除なので後ろから処理
  set itemAppPathURL to ocidChooseArray's objectAtIndex:(numCntArray - 1)
  ###ボリューム名を取得して
  set listPathVolumeName to (itemAppPathURL's getResourceValue:(reference) forKey:(refMe's NSURLVolumeNameKey) |error|:(reference))
  set strPathVolumeName to (item 2 of listPathVolumeName) as text
  ###外部ボリュームのものは削除
  if strPathVolumeName is "Preboot" then
    log strPathVolumeName
  else if strPathVolumeName is not strVolumeName then
ocidChooseArray's removeObjectAtIndex:(numCntArray - 1)
  end if
  set numCntArray to numCntArray - 1
end repeat

set strOpenContentPath to (item 1 of ocidChooseArray)'s |path| as text

if strOpenContentPath contains "ProfileHelper.app" then
return "設定変更必要ありません"
end if

################################
##アプリケーションのURLを取得する
################################
set ocidAppPath to "/System/Library/CoreServices/ProfileHelper.app" as text
set ocidAppPathStr to refMe's NSString's stringWithString:(ocidAppPath)
set ocidAppPath to ocidAppPathStr's stringByStandardizingPath()
set ocidAppPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidAppPath) isDirectory:false)

###選んだアプリケーションのバンドルID
set ocidAppBunndle to (refMe's NSBundle's bundleWithURL:(ocidAppPathURL))
set ocidBunndleID to ocidAppBunndle's bundleIdentifier
###IF用にテキストにしておく
set strBunndleID to ocidBunndleID as text
## com.apple.mcx.ProfileHelper
log strBunndleID

################################
##デフォルトに設定する
################################
set appShardWorkspace to refMe's NSWorkspace's sharedWorkspace()
appShardWorkspace's setDefaultApplicationAtURL:(ocidAppPathURL) toOpenContentType:(ocidUTType) completionHandler:(missing value)


################################
##設定後に 値の確定
################################

set strFilePath to "~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.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)
### PLISTを読み込む
set ocidPlistDict to refMe's NSMutableDictionary's alloc()'s initWithContentsOfURL:(ocidFilePathURL)
###LSHandlers Array
set ocidLSHandlersArray to ocidPlistDict's objectForKey:"LSHandlers"
###項目数の数だけ繰り返し
repeat with itemLSHandlers in ocidLSHandlersArray
  ###コンテンツタイプを取得して
  set ocidLSHandlerContentType to (itemLSHandlers's valueForKey:"LSHandlerContentType")
  ###設定項目のコンテンツタイプと同じなら
  set strLSHandlerContentType to ocidLSHandlerContentType as text
  if strLSHandlerContentType is strUTI then
    ###変更前の値
    set ocidRoleViewer to (itemLSHandlers's valueForKey:"LSHandlerRoleViewer")
    set ocidRoleAll to (itemLSHandlers's valueForKey:"LSHandlerRoleAll")
    set ocidRoleAll to (itemLSHandlers's valueForKey:"LSHandlerRoleEditor")
    set ocidRoleShell to (itemLSHandlers's valueForKey:"LSHandlerRoleShell")
    log ocidRoleViewer as text
    log ocidRoleAll as text
    log ocidRoleAll as text
    log ocidRoleShell as text
    ####値を変更する
(itemLSHandlers's setValue:(strBunndleID) forKey:"LSHandlerRoleViewer")
(itemLSHandlers's setValue:(strBunndleID) forKey:"LSHandlerRoleAll")
(itemLSHandlers's setValue:(strBunndleID) forKey:"LSHandlerRoleEditor")
(itemLSHandlers's setValue:(strBunndleID) forKey:"LSHandlerRoleShell")
    ####変更後の値
    log (itemLSHandlers's valueForKey:"LSHandlerRoleViewer") as text
    log (itemLSHandlers's valueForKey:"LSHandlerRoleAll") as text
    log (itemLSHandlers's valueForKey:"LSHandlerRoleEditor") as text
    log (itemLSHandlers's valueForKey:"LSHandlerRoleShell") as text
  end if
  
end repeat
###保存
set boolDone to ocidPlistDict's writeToURL:(ocidFilePathURL) atomically:true
log boolDone as boolean


#############################
###CFPreferencesを再起動
#############################
#####CFPreferencesを再起動させて変更後の値をロードさせる
set strCommandText to "/usr/bin/killall cfprefsd" as text
do shell script strCommandText


#############################
###LaunchServicesを再起動
#############################
####lsregister初期化
(*#色々やってみたが不具合の方が多いので停止
set strCommandText to "/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -kill -seed" as text
do shell script strCommandText
*)


|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat 2024 Acrobat AddOn Acrobat Annotation Acrobat AppleScript Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat GentechAI Acrobat JS Acrobat JS Word Search Acrobat Maintenance Acrobat Manifest Acrobat Menu Acrobat Merge Acrobat Open Acrobat PDFPage Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat Print Acrobat Python Acrobat Reader Acrobat Reader Localized Acrobat Reference Acrobat Registered Products Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat URL List Mac Acrobat URL List Windows Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin ConfigCode Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin NetWork Admin Permission Admin Pkg Admin Power Management Admin Printer Admin Printer Basic Admin Printer Custompapers Admin SetUp Admin SMB Admin softwareupdate Admin Support Admin System Information Admin TCC Admin Tools Admin Umask Admin Users Admin Volumes Admin XProtect Adobe Adobe AUSST Adobe Bridge Adobe Documents Adobe FDKO Adobe Fonts Adobe Reference Adobe RemoteUpdateManager Adobe Sap Code AppKit Apple AppleScript AppleScript Duplicate AppleScript entire contents AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Video Applications AppStore Archive Archive Keka Attributes Automator BackUp Barcode Barcode Decode Barcode QR Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome Chromedriver CIImage CityCode CloudStorage Color Color NSColor Color NSColorList com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Desktop Position Device Diff Disk do shell script Dock Dock Launchpad DropBox Droplet eMail Encode % Encode Decode Encode HTML Entity Encode UTF8 Error EXIFData exiftool ffmpeg File File Name Finder Finder Window Firefox Folder FolderAction Font List FontCollections Fonts Fonts Asset_Font Fonts ATS Fonts Emoji Fonts Maintenance Fonts Morisawa Fonts Python Fonts Variable Foxit GIF github Guide HTML Icon Icon Assets.car Illustrator Image Events ImageOptim Input Dictionary iPhone iWork Javascript Jedit Ω Json Label Language Link locationd lsappinfo m3u8 Mail Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Microsoft Fonts Microsoft Office Microsoft Office Link Microsoft OneDrive Microsoft Teams Mouse Music Node Notes NSArray NSArray Sort NSAttributedString NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSGraphicsContext Crop NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMetadataItem NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSet NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSUbiquitous NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth PDF PDF Image2PDF PDF MakePDF PDF nUP PDF Pymupdf PDF Pypdf PDFContext PDFDisplayBox PDFImageRep PDFKit PDFKit Annotation PDFKit AnnotationWidget PDFKit DocumentPermissions PDFKit OCR PDFKit Outline PDFKit Start PDFPage PDFPage Rotation PDFView perl Photoshop PlistBuddy pluginkit plutil postalcode PostScript PowerShell prefPane Preview Python Python eyed3 Python pip QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver Script Editor Script Menu SF Symbols character id SF Symbols Entity Shortcuts Shortcuts Events sips Skype Slack Sound Spotlight sqlite StandardAdditions StationSearch Subtitles LRC Subtitles SRT Subtitles VTT Swift swiftDialog System Events System Settings 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 Weather webarchive webp Wifi Windows XML XML EPUB XML HTML XML LSSharedFileList XML LSSharedFileList sfl2 XML LSSharedFileList sfl3 XML objectsForXQuery XML OPML XML Plist XML Plist System Events XML RSS XML savedSearch XML SVG XML TTML XML webloc XML xmllint XML XMP YouTube Zero Padding zoom