How to programatically add folder to Spotlight "do not index"?

According to an answer here, a folder can be excluded from Spotlight indexing (achieving the same effect as adding it to the Privacy tab, although the folder won't actually be listed there) by either

  • adding .noindex to the end of the folder's name, or
  • creating an empty file .metadata_never_index inside the folder (eg with touch folder/.metadata_never_index)

You will need to restart Finder after adding .metadata_never_index, either killall Finder from Terminal or logout from the Apple menu and then log back in. This method doesn't work in Mojave and later.


You have to stop and start the launchd service called com.apple.metadata.mds. So after:

sudo defaults write /Volumes/foo/.Spotlight-V100/VolumeConfiguration.plist Exclusions -array-add '/path/to/folder'

do:

sudo launchctl stop com.apple.metadata.mds && sudo launchctl start com.apple.metadata.mds

The VolumeConfiguration.plist has moved

It now resides in /System/Volumes/Data/.Spotlight-V100/VolumeConfiguration.plist.

You can easily edit it using /uar/libexec/PlistBuddy

Reading

sudo /usr/libexec/PlistBuddy -c "Print :Exclusions" /System/Volumes/Data/.Spotlight-V100/VolumeConfiguration.plist

Writing

The zero indicates the element in the array or in this case the beginning of the array

sudo /usr/libexec/PlistBuddy -c "Add :Exclusions:0 string '/path/to/folder'" /System/Volumes/Data/.Spotlight-V100/VolumeConfiguration.plist

Deleting

The zero indicates the the first item in the array

sudo /usr/libexec/PlistBuddy -c "Delete :Exclusions:0 string" /System/Volumes/Data/.Spotlight-V100/VolumeConfiguration.plist

Restart the daemon

Easiest solution to get the change to take effect is reboot, but you can also tell Launchd to restart the mdworkers

sudo launchctl stop com.apple.metadata.mds
sudo launchctl start com.apple.metadata.mds