If you don't mind changing a particular Finder preference, i.e. When performing a search:, then the following will work.
First, in Finder > Preferences... > Advanced, set When performing a search: to: Search the Current Folder
Next, create an Automator Service workflow with its default settings (Service receives selected text in any application) and add a Run AppleScript action, replacing the default code with the code below:
on run {input, parameters}
tell application "Finder"
activate
open (POSIX file "/")
end tell
delay 0.5 -- # Adjust as necessary or comment out/remove if not needed.
tell application "System Events"
keystroke "f" using command down
keystroke input as text
keystroke return
end tell
end run
Save the Automator Service workflow, e.g. Search Selected Text in Finder
If you want to add a programatic test and preference change for When performing a search: being set to Search the Current Folder, then add the following code directly after on run {input, parameters}
and before the tell application "Finder"
block.
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"
delay 1 -- # Adjust as necessary or comment out/remove if not needed.
end if
An alternative, is to leave the default Finder preference for When performing a search: to Searching This Mac and do the following:
- Open a new Finder window to the Macintosh HD.
- Press: ⌘F
- On the Search bar, click the “Macintosh HD” button.
- On the Search bar, click the Save button.
Follow through to save the search. In this instance, e.g.:
- Save As: Searching “Macintosh HD”
- Where: Saved Searches
- [] Add To Sidebar (unchecked)
In the Run AppleScript action of the Automator Service workflow, replace open (POSIX file "/")
with the following example code, adjusted for your system and how/where you saved the Search:
open POSIX file "/Users/me/Library/Saved Searches/Searching “Macintosh HD”.savedSearch"
The example AppleScript code would then be:
on run {input, parameters}
tell application "Finder"
activate
open POSIX file "/Users/me/Library/Saved Searches/Searching “Macintosh HD”.savedSearch"
end tell
delay 0.5 -- # Adjust as necessary or comment out/remove if not needed.
tell application "System Events"
keystroke "f" using command down
keystroke input as text
keystroke return
end tell
end run
This latter method leaves the default setting in Finder alone and achieves the goal without using mouse clicks or clicking buttons from the Automator Service workflow.
Note: The example AppleScript code is just that and may require additional delay
commands where appropriate/needed, e.g. between the keystroke
commands as/if necessary.