Hello. I understand how to change the color of a tag, but I want to assign the file a name tag.
For example, if I want some files to be tagged “old”, and that it should be done through a script. Grateful for answers
You may use this code borrowed to Shane Stanley.
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
property |NSURL| : a reference to current application's |NSURL|
property NSOrderedSet : a reference to current application's NSOrderedSet
property NSURLTagNamesKey : a reference to current application's NSURLTagNamesKey
-- Fetch tags; pass a POSIX path
on returnTagsFor:POSIXPath
set thisURL to |NSURL|'s fileURLWithPath:POSIXPath -- make URL
set {theResult, theTags, theError} to thisURL's getResourceValue:(reference) forKey:NSURLTagNamesKey |error|:(reference)
if theResult as boolean is false then error (theError's |localizedDescription|() as text)
if theTags = missing value then return {} -- because when there are none, it returns missing value
return theTags as list
end returnTagsFor:
-- Replace tags; pass a list of the new tags plus POSIX path
on setTags:tagList forItem:POSIXPath
set thisURL to |NSURL|'s fileURLWithPath:POSIXPath -- make URL
set {theResult, theError} to thisURL's setResourceValue:tagList forKey:NSURLTagNamesKey |error|:(reference)
if theResult as boolean is false then error (theError's |localizedDescription|() as text)
return true
end setTags:forItem:
-- Add tags; pass a list of the new tags plus a POSIX path
on addTags:tagList forItem:POSIXPath
set thisURL to |NSURL|'s fileURLWithPath:POSIXPath -- make URL
-- get existing tags
set {theResult, theTags, theError} to thisURL's getResourceValue:(reference) forKey:NSURLTagNamesKey |error|:(reference)
if theResult as boolean is false then error (theError's |localizedDescription|() as text)
if theTags ≠ missing value then -- make list of old and new tags
set tagList to (theTags as list) & tagList
set tagList to (NSOrderedSet's orderedSetWithArray:tagList)'s |allObjects|() -- delete any duplicates
end if
set {theResult, theError} to thisURL's setResourceValue:tagList forKey:(NSURLTagNamesKey) |error|:(reference)
if theResult as boolean is false then error (theError's |localizedDescription|() as text)
return true
end addTags:forItem:
set POSIXPath to POSIX path of (choose file)
-- Apply a list of tags
my setTags:{"old"} forItem:POSIXPath
-- Add a list of tags to existing ones
-- my addTags:{"old"} forItem:POSIXPath
Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) jeudi 27 février 2020 12:33:59
You can do it with my FileManagerLib, available here:
https://www.macosxautomation.com/applescript/apps/Script_Libs.html
use AppleScript version "2.5" -- macOS 10.11 or later
use script "FileManagerLib" version "2.3.3"
use scripting additions
set theFile to (choose file)
set tags of theFile to {"old"}
-- or
add tags {"old"} to theFile
The underlying code is similar to that Yvan posted.