Get PIDs of all open windows on MacOS - macos

I tried to use the following AppleScript to get the PIDs of all the windows (including ones that are minimized). This script doesn't get the PIDs of windows on other desktops.
Is there any workaround for this so I can still get a list of opened windows across all desktops without having to activate individual processes and checking if they have windows?
tell application "System Events"
repeat with proc in (every process)
if exists(first window of proc) then
set pid to unix id of proc
log pid
end if
end repeat
end tell
PS, I'm not too proficient with AppleScript. I've managed to hack this together using StackOverflow. This might not be the most efficient way to do what I'm trying to do.

Looks like I got this to work with this ugly bash-applescript hack
osascript -e "tell application \"System Events\"
repeat with proc in (processes where background only is false)
set pname to name of proc
log pname
end repeat
end tell" 2>&1 |
while read line
do
echo "process " $line
pgrep $line
done
This prints something like
process Finder
818
process Google Chrome
3730
3734
3740
5838
process iTerm2
3750
4210
process Sublime Text
3822
Where PID 818 belongs to the Finder process and so on.

Related

Killing all Adobe Background processes when not needed MAC

This code and question is following on from perfectfiasco question and answer by Ted Wrigley.
I too find it crazy how many processes Adobe runs in the background - even when finder extensions are disabled and not using any apps.
I am trying to create something similar but for 3 additional apps also Lightroom / creative cloud and adobe bridge also and have edited it slightly to include all the other processes that Adobe run in the background. Any idea if I have added these correctly?
Not entirely sure how to separate apps from processes and if its necessary to killall for apps or just quit command?
Is it fine to force quit process and apps like this?
Something I have noticed is that if lots of adobe processes are quit then it launches this daemon "AdobeCRDaemon" is that expected?
Not sure what to put here now several other processes have been added - tell process "AGMService"
Does anything else in the code need updating for current macOS Monterey ?
Thank you in advance for any clarification
use AppleScript version "2.4"
use framework "AppKit"
use scripting additions
property NSWorkspace : class "NSWorkspace"
on run
set workSp to NSWorkspace's sharedWorkspace()
set notifCent to workSp's notificationCenter()
tell notifCent to addObserver:me selector:"someAppHasTerminated:" |name|:"NSWorkspaceDidTerminateApplicationNotification" object:(missing value)
end run
on idle
-- we don't use the idle loop, so tell the system let the app sleep. this comes out of idle once an hour
return 3600
end idle
on someAppHasTerminated:notif
set termedApp to (notif's userInfo's valueForKey:"NSWorkspaceApplicationKey")
set termedAppName to (termedApp's localizedName) as text
-- I'm guessing at the localized names for Photoshop and Illustrator. you may need to alter these
if termedAppName is "Adobe Photoshop 2022" or termedAppName is "Adobe Lightroom Classic" or termedAppName is "Adobe Bridge 2022" or termedAppName is "Adobe Lightroom" or termedAppName is "Creative Cloud" then
-- close the service here
tell application "System Events"
tell process "AGMService"
if its accepts high level events is true then
tell application "AGMService" to quit
tell application "Adobe Desktop Service" to quit
tell application "CCLibrary" to quit
tell application "CCXProcess" to quit
tell application "Core Sync" to quit
tell application "Creative Cloud Helper" to quit
else
do shell script "killall AGMService"
do shell script "killall Adobe Desktop Service"
do shell script "killall CCLibrary"
do shell script "killall CCXProcess"
do shell script "killall Core Sync"
do shell script "killall Creative Cloud Helper"
end if
end tell
end tell
end if
end someAppHasTerminated:
This is a deeply unsafe way to do this, but I've replaced the nested tell hell in onAppHasTerminated this:
do shell script "pkill -i -f adobe"
My personal script looks like this.
I had the same problem.
Just run this command in terminal:
kill $(ps aux | grep -i '.adobe' | grep -v grep | awk '{print $2}')

how to close an active document in Mac OS using shell script

I am closing active document using apple script as below
tell application "Microsoft Word"
activate
try
if not (exists active document) then error number -128
close active document saving yes
on error
end try
end tell
want to do similar action using shell script. I want to gracefully close it and don't want to use kill command . And I don't want to use osascript to call an apple script . I want a graceful way using native shell commands
Hi you can use osascript in the shell code
#!/bin/sh
osascript <<EOF
tell application "$1"
close (every window whose name is "$2")
end tell
EOF
Compile this code and make filename.sh
or you can use
#!/bin/sh
osascript <<EOF
tell application "Preview"
close (every window whose name is "$1")
end tell
EOF
To use this from cmd type $./file_name Preview application name
Here I used the reference of https://ss64.com/osx/osascript.html

Using apple script to find out and compare process path by PID

I am using Apple Script to find the process PID by name, like ...
set appName to "KKK"
tell application "System Events"
set processPID to (unix id of processes whose name is appName)
end tell
With this script, I can know about PIDs of all processes which name is "KKK".
But I have a question here.
For example, there has three "KKK" process, "/FolderA/KKK", "FolderB/KKK", "FolderC/KKK"
I want to kill the process of "/FolderA/KKK", so I need to know which PID is belong to "/FolderA/KKK".
After run my script, I can get three PIDs, what can I actually do in Apple Script to distinguish which PID is what I want? (Maybe to get the process path by PID?)
Thank you
Instead of the name check for the path of the application, this is an example checking for Messages.app.
set appPath to "/Applications/Messages.app"
tell application "System Events"
set processPID to (unix id of 1st process whose POSIX path of application file is appPath)
end tell
It also can be done using the following:
do shell script "kill -9 $(ps -x | awk '/[F]olderA\\/KKK/{print $1}')"
You can also add ; exit 0 to the end to eat an error if the app isn't running and have no need to check or trap otherwise:
do shell script "kill -9 $(ps -x | awk '/[F]olderA\\/KKK/{print $1}'); exit 0"

Access built-in Power Manager? states

Im trying to write a super simple applescript that will launch the OneDrive App, or ensure it is open, whenever the machine's power source is set to plugged in, and will quit, or make sure is closed, when the power source is set to battery.
I'm having trouble finding how to access the built-in "power indicator" in Yosemite. All of my searches lead to old, irrelevant results from years ago.
Edit: I think I will have to use a do shell script within the applescript using pmset -g batt
Now drawing from 'AC Power'
-InternalBattery-0 100%; charged; 0:00 remaining
And parse this result, but I am not sure how.
Edit: Here it is for anyone in the future who may want something similar:
global appName
on appIsRunning()
tell application "System Events" to (name of processes) contains appName
end appIsRunning
on acIsConnected()
return (do shell script "system_profiler SPPowerDataType | grep -q 'Connected: Yes' && echo \"true\" || echo \"false\"") as boolean
end acIsConnected
on toggleApp()
if my acIsConnected() then
if not my appIsRunning() then
tell application "Finder"
open application file (appName & ".app") of folder "Applications" of startup disk
end tell
end if
else
tell application appName
quit
end tell
end if
end toggleApp
-- This will only be executed once.
on run
set appName to "OneDrive"
end run
-- This will be executed periodically, specified in seconds, every return.
on idle
my toggleApp()
-- Execute every 2 minutes.
return 120
end idle
-- Not mandatory, but useful for cleaning up before quiting.
on quit
-- End handler with the following line.
continue quit
end quit
Here is a one-liner that polls for connected status, since I guess you can have less than 100% and still be connected (charging).
set acConnected to (do shell script "system_profiler SPPowerDataType |grep -q 'Connected: Yes' && echo \"true\" || echo \"false\"") as boolean
Here's another one liner...
set acConnected to last word of paragraph 1 of (do shell script "ioreg -w0 -l | grep ExternalChargeCapable")
If you are happy to use a third party tool, you can avoid polling for the battery state. This will make your script more efficient.
Power Manager can run AppleScripts when the battery state changes. How to Run a Command When Switching to Battery Power, walks through how to set this up for scripts.
Swap out the #!/bin/sh for #!/usr/bin/osascript in the script, and you can use AppleScript.
Disclaimer: I wrote Power Manager and can answer comments about how it works.
Provided you have battery icon on screen's top right:
tell application "System Events" to tell process "SystemUIServer" ¬
to value of attribute "AXDescription" of ¬
(first menu bar item whose value of attribute "AXDescription" ¬
begins with "Battery") of menu bar 1
You get "Battery: Charged" or "Battery: Calculating Time Remaining… " or something else

Can't make Unix ID of Process into text?

I have a modbook with a glitchy digitizer board. Until I can re-shield the cable that is causing the glitch I just want to turn the digitizer off. I found a page which taught me some code and I used it successfully last night. Upon reboot, however, it doesn't work anymore:
The script:
tell application "System Events"
set PTD to (unix id of process "PenTabletDriver") as text
do shell script "kill -STOP " & quoted form of (PTD)
end tell
The error message:
error "Can’t make «class idux» of «class prcs» \"PenTabletDriver\" of
application \"System Events\" into type text." number -1700 from
«class idux» of «class prcs» "PenTabletDriver" to text
Can I alter the code somehow to fix this problem?
PS:
I have read this post and, though it's similar, I do not understand how it could be applied to my problem.
Life is too short to mess with AppleScript. Try running the following command at the terminal prompt:
pkill -STOP PenTabletDriver
Also, check your login items to see if the driver is automatically started each time you log in. (More likely, though, is that it's configured to start at boot time via launchd.)
You can save the following script in a little applet:
set shellStr to "pkill -STOP PenTabletDriver"
do shell script shellStr
and run it whenever you need.
I think the other answers make a good point, a shell command is nice and quick. BUT, if you must have it in AppleScript, this seems to work for me....
tell application "System Events"
set PTD to (unix id of process "iTunes")
do shell script "kill -STOP " & quoted form of (PTD as text)
end tell
which results to
tell application "System Events"
get unix id of process "iTunes"
--> 37987
do shell script "kill -STOP '37987'"
--> error number -10004
end tell
tell current application
do shell script "kill -STOP '37987'"
--> ""
end tell
The Process ID is just a number so there is no need to quote it...
tell application "System Events"
set PTD to (unix id of process "iTunes")
do shell script "kill -STOP " & PTD
end tell
The above code is sufficient.

Resources