File path of selected file

I almost never need to ask anything on this fantastic Forum, always find what I need by searching… but, this simple problem beats me and my searches:

I want to get the filepath of the file selected in Finder, here is my script:

tell application "Finder"
	
	set selectedItem to selection
	set filePath to (get file path of selectedItem) as text
	
	display dialog filePath
	
end tell

I get an error telling me that Finder could not get path… the thing is that in the eventlog it has the full path to the file:

tell application “Finder”
get selection
{folder “Export” of startup disk}
get path
“Finder drabbades av ett fel: Det gÃ¥r inte att hämta path.”

(Last row (The error) in the eventlog is in Swedish if you wonder :wink:

Anybody knows how to get the full path?

Regards / Johan

Hi, Johan.

The Finder’s selection returns a list of the selected items. Even if only one item is selected, the result is a list ” hence the braces {} in {folder “Export” of startup disk}. If you know that the list only contains one item, you can coerce it directly to Unicode text:

tell application "Finder"
	set filePath to selection as Unicode text --> The path to the one selected item.
end tell

Otherwise, you have to repeat through the list:

tell application "Finder"
	set theSelection to selection
	repeat with i from 1 to (count theSelection)
		set filePath to (item i of theSelection) as Unicode text 
		-- Do something with filePath
	end repeat
end tell

Thanks Nigel, now I see life more clearly :wink:

This IS one of the best forums I know of…

I will post my final script when done.

/johan

Hello Nigel,

Thanks for the precision. I wanted to copy the result of the script to the Clipboard. The Finder basics say that it is not emplemented yet … Is there a workaround to easily have the path of a file without having to type it ??? Thanks in advance.

Model: iMac G5 1.6 MHZ - 2GB
AppleScript: 1.10.7
Browser: Safari 419.3
Operating System: Mac OS X (10.4)

It seems the Finder basics are kidding :wink: :smiley:

tell application "Finder"
	set filePath to selection as Unicode text
	set the clipboard to filePath
end tell

Ciao
Farid

:slight_smile:

It’s the Finder’s copy command that’s not implemented yet. The command set the clipboard is in the StandardAdditions and works with things that are already in the script, such as the Unicode text that the Finder’s just returned.