Finder.app: Select an Folder/File on teh Desktop

If there’s a better way to select a folder/file (without opening its container window) on the desktop, feel free to correct me. My solution is a bit strange:


tell application "Finder"
	set collapsed of windows to true
	set selection to (folder "2018" of desktop)
	set collapsed of windows to false
end tell

I did not want to continue the argument, but it is very bad that your conclusion is incorrect and will mislead others. The empty selection is not the result of the script, but the result of your extra manual manipulation in the sidebar. You would also restart the computer to be sure - my script returns an empty selection.

And what is the concept of selection in the Finder? The selection in the frontmost Finder window. If, after the selection, make another window (in which nothing is selected) as the front window, and then read the selection property, then naturally you will get an empty selection.

Hi.

KniazidisR’s script works as advertised on my Mojave system, regardless of anything being selected in sidebars. The empty list is the result of the second collapsed setting.

A variation which also works is actually to close and reopen any open Finder Windows. This makes the windows simply disappear and reappear on my system, instead of swooping in and out of the Dock, but it may depend on my own preference settings.

tell application "Finder"
	set tofw to target of Finder windows
	close tofw
	set selection to (folder "2018" of desktop)
	open tofw
end tell

Thanks, @Nigel Garvey,

I tested your script on Catalina, and I think it’s better than my solution, as it works about 2 times faster. So fast that I had to add an automated delay to keep things running smoothly.


tell application "Finder"
	set tofw to target of Finder windows
	close tofw
	repeat while ((get count Finder windows) > 0)
		delay 0.02
	end repeat
	set selection to (folder "2018" of desktop)
	open tofw
end tell

Not sure if this helps.

tell application "Finder"
	set myFolder to (folder "2018" of desktop)
	--set selection to desktop
	set selection to myFolder
	open myFolder
end tell

I don’t understand what you mean by not opening the container window.
The desktop is always open.

The icons of files and folders on the Desktop can be selected either on the Desktop itself or in the Finder window which opens when you open the user’s “Desktop” folder. The Finder’s scripting commands reveal and select both take the latter approach:

tell application "Finder" to select folder "2018" of desktop
--> folder "Desktop"'s Finder window opens if not open already. Folder "2018" is selected therein.

KniazidisR’s hack selects the icon on the Desktop itself (in both Mojave and Catalina) should this be deemed necessary.