Can't get POSIX file

This an automator workflow (which entirely consists of an AppleScript) to search for all the files in a current folder.

on run {input, parameters}
	tell application "Finder"
		activate
		set theWin to window 1
		set thePath to (POSIX path of (target of theWin as alias))
		open POSIX file thePath
	end tell
	delay 0.5
	tell application "System Events"
		keystroke "f" using command down
		delay 0.5
		set the clipboard to "NOT kind:folder"
		keystroke "v" using command down	
	end tell
end run

(FWIW, the first part is borrowed from here: Mac AppleScript Finder: How to put the path of the current Finder window on the clipboard | alvinalexander.com)

But for some reason it cannot get the path of a currently opened directory, and gives me error messages like this one:

Finder got an error: Can’t get POSIX file “/Users/john/Documents/”.

How to fix this?

Out of curiosity… isn’t the folder already open? Why do you want to open it again?

By the way, that post on Alvin Alexander’s site is ten years old so things may have changed.

1 Like

Thanks a lot, Fredrik, this works. The current version of script is:

on run {input, parameters}
	tell application "Finder"
		activate
		set theTarget to (target of window 1)
		open theTarget
	end tell
	delay 0.5
	tell application "System Events"
		keystroke "f" using command down
		delay 0.5
		keystroke "NOT kind:folder"
	end tell
end run

When I start it, it opens a search window with two tabs, the first is “This Mac” and the second is the current folder:

image

By default, the script searches in “This Mac”. Do you know how to make it search in the current folder instead, without changing Finder settings?

This script is to show all the files in the current folder and in its subfolders. Some file managers call it “flat view”.

Your script uses GUI scripting, which is best avoided. If you were to say why you need to show a list of files, then most likely you would be offered a better approach.

Thanks for suggestions! Unfortunately Automator solutions doesn’t work for me for some reason. The first Automator solution doesn’t make any visual effect and the second produces an error. (Does they work for you?)

I have also tried the following two lines from this post, but they give me an error.

if (do shell script "defaults read com.apple.finder FXDefaultSearchScope") is not "SCcf" then
    do shell script "defaults write com.apple.finder FXDefaultSearchScope SCcf; killall Finder"
end if

To change the behavior of the preferred search location, go to the advance section of Finder preferences:
Screenshot 2023-08-30 at 10.19.22 AM

1 Like