How to make script out of focus in AppleScript?
This will do what I think you're looking for. I removed the 'choice of one' from the beginning as it didn't seem relevant to the workflow.
I'm using an activeApp variable to call the app forwards after the dialogs. If you use System Events to call forwards it will not restore the frontmost window.
By using tell me
instead of tell application "System Events"
except where necessary, you can avoid the complication of the modal dialog stealing focus & not returning to your frontmost window afterwards.
Adding & quoted form of
to the shellscript will work in more cases. Some apps will error without it, including Automator itself.
The Automator service receives no input
from any application
I've left in a lot of debug, in the form of dialogs, to observe the progress.
on run {input, parameters}
tell me
tell application "System Events" to set activeApp to name of first application process whose frontmost is true
-- Back up original clipboard contents:
set savedClipboard to the clipboard
display dialog ("Original clip - " & (the clipboard))
activate application activeApp
tell application "System Events" to keystroke "c" using command down
delay 1
display dialog ("Copied clip - " & (the clipboard))
set theSelectedText to the clipboard
set theModifiedSelectedText to do shell script "echo " & quoted form of theSelectedText & " | tr a-z A-Z;"
display dialog {"Modified clip - " & theModifiedSelectedText}
activate application activeApp
set the clipboard to theModifiedSelectedText
delay 1
tell application "System Events" to keystroke "v" using {command down}
-- Restore clipboard:
delay 1
set the clipboard to savedClipboard
display dialog ("Restored clip - " & (the clipboard))
end tell
set input to {}
return input
end run