Delete Alias From Desktop When Original File Is Moved to Trash

Hi there,

I've written a script which deletes alias files from the desktop if the original file is in the trash.

The macro is triggered when the trash folder adds an item, but I'm not sure:

  • Is a Semaphore Lock necessary?

  • Which Timeout should I use in a Semaphore Lock?

I'm a complete AppleScriptObjC newbie, so any suggestions are more than welcome :slight_smile:

-- Delete alias files from desktop if original file is in the trash

-- NOTE: This script does NOT move to trah. It directly deletes alias files. You can't undo it.

use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

property theTrash_Path_HFS : (path to trash folder from user domain) as string

tell application "System Events"
	try
		set theDesktopAlias_Paths to POSIX path of (items of desktop folder whose visible is true and type identifier = "com.apple.alias-file")
		
	on error error_message number error_number
		if the error_number is not -128 then display alert "Error " & error_number message error_message as warning
		return
	end try
end tell

if theDesktopAlias_Paths ≠ {} then
	try
		set fileManager to current application's NSFileManager's defaultManager()
		
		repeat with thisAlias_Path in theDesktopAlias_Paths
			set thisAlias_Path to thisAlias_Path as string
			
			set thisAlias_URL to (current application's class "NSURL"'s fileURLWithPath:thisAlias_Path)
			set thisOriginal_URL to (current application's class "NSURL"'s URLByResolvingAliasFileAtURL:thisAlias_URL options:0 |error|:(missing value))
			
			set thisOriginal_URL_string to thisOriginal_URL as string
			
			if (thisOriginal_URL_string starts with theTrash_Path_HFS) then
				set deleteAlias to (fileManager's removeItemAtURL:thisAlias_URL |error|:(missing value))
			end if
		end repeat
		
	on error error_message number error_number
		if the error_number is not -128 then display alert "Error " & error_number message error_message as warning
		return
	end try
end if