Following the discussions here and elsewhere, I’ve put together a script library for retrieving Spotlight metadata, and conducting Spotlight-style searches.
Fetching metadata for a file is simple:
use mdLib : script "Metadata Lib" version "1.0.0"
use scripting additions
set theFile to choose file
set theMetadata to mdLib's fetchMetadataFor:theFile
The command accepts a file, alias, NSURL or POSIX path, and returns the result as an AppleScript record. It’s also quicker than using mdls
. There are also variations for things like just getting the keys as string, and getting the results as a pair of matching lists.
(If you followed the earlier discussions, you’ll see that the code for this a lot simpler than I posted there.)
Searching is also fairly simple, although you need to understand the basics of predicates. So, for example, this will find all the .txt
files on your desktop:
set theFolder to path to desktop
mdLib's searchFolders:{theFolder} searchString:"kMDItemFSName ENDSWITH[c] '.txt'" searchArgs:{}
The result will be a list of POSIX paths.
You can also search for other attributes. For example, to find all the .txt
files and their sizes:
set theFolder to path to desktop
mdLib's searchFolders:{theFolder} searchString:"kMDItemFSName ENDSWITH[c] %@" searchArgs:{".txt"} forAttributes:{"kMDItemFSSize"}
There’s also a utility handler that lets you convert saved Finder searches into predicate strings.
You can download it here: https://www.macosxautomation.com/applescript/apps/Metadata_Lib_stuff.zip.