Copy Current Path Automator

41 Views Asked by At

I found the below tutorial on how to write an automator script to grab the current path of the finder window. I'd like to make it more robust and modify it so it grabs the path of the following based on the condition of what is selected. Is that possible? If so how?

  1. If nothing in the finder window is selected → Copy the path of the directory (code below)
  2. If a file is selected copy the path to the file (#1 + /filename)
  3. If a folder in the finder window is selected copy the path to the folder (#1 + /foldername)
try
    tell application "Finder" to set the clipboard to POSIX path of (target of window 1 as alias)
on error
    beep
end try

https://apple.stackexchange.com/questions/47216/copying-the-current-directorys-path-to-the-clipboard

Current code copies just the directory path

1

There are 1 best solutions below

0
vadian On BEST ANSWER

There is a fourth case: Nothing is selected and there is no Finder window. And it's also possible that there are multiple Finder windows.

The logic which covers all cases is as follows:

  • If something (one or more items) is selected copy the path of the first selected item
  • If nothing is selected and there are one or more Finder windows copy the path of the first Finder window.
  • If nothing is selected and there is no Finder window do nothing.

tell application "Finder"
    set selectedItems to selection
    if selectedItems is not {} then
        set the clipboard to POSIX path of (item 1 of selectedItems as alias)
    else if exists window 1 then
        set the clipboard to POSIX path of (target of window 1 as alias)
    end if
end tell