Removing login items for users via a bash script

michael_rowland
New Contributor

I am needing to remove some obsolete login items from our classroom machines

I'm trying the following

#!/bin/bash -v
exec 2>&1

sudo -u $3 /usr/bin/osascript -e 'tell application "System Events" to delete login item "PCClient"'
sudo -u $3 /usr/bin/osascript -e 'tell application "System Events" to delete login item "fthf02.op.ac.nz"'

It works fine running it manually on a client but once I run it as a login policy I get

Script result: 
sudo -u $3 /usr/bin/osascript -e 'tell application "System Events" to delete login item "PCClient"'
43:53: syntax error: A class name can’t go after this identifier. (-2740)
sudo -u $3 /usr/bin/osascript -e 'tell application "System Events" to delete login item "fthf02.op.ac.nz"'
43:53: syntax error: A class name can’t go after this identifier. (-2740)

Any ideas what I'm doing wrong?

3 REPLIES 3

pblake
Contributor III

Have you tried adding in a sleep 30? Perhaps it is running too quickly at login.

bpavlov
Honored Contributor
#!/bin/bash

loggedInUser=$( ls -l /dev/console | awk '{print $3}' )
loggedInPID=$( ps -axj | awk "/^$loggedInUser/ && /Dock.app/ {print $2;exit}" )

/bin/launchctl bsexec "${loggedInPID}" sudo -u "${loggedInUser}" /usr/bin/osascript -e 'tell application "System Events" to delete login item "PCClient"'

Give this script a try. I got this a few months ago from a similar question someone else posed.

gregneagle
Valued Contributor

bpavlov: Be sure to test this technique under El Capitan. There might be some changes that affect this technique...