MacOS – How to programatically add folder to Spotlight “do not index”

applescriptcommand linemacosspotlightterminal

Is there any way to programmatically add a folder to Spotlight's "Privacy" tab?
Either through Terminal or Applescript?

Often I want to click on an item in Spotlight results in Finder, and have that item's folder no longer be indexed.

I found that if you

sudo defaults read /Volumes/foo/.Spotlight-V100/VolumeConfiguration.plist Exclusions

you can see an array with all the items excluded.

But if you try to

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

it does NOT get added to the Privacy tab in the Spotlight Preference Panel, nor does it get de-indexed.

Best Answer

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.