Delete Users Script

user-WGEZezkEyE
New Contributor

We have our macs setup with a local admin account and student login with their AD info and creates a mobile account. Does anyone have a script they use that works to delete all the users minus the admin account?

2 REPLIES 2

_gsm
New Contributor III

This works for me. I have not tried it with mobile accounts.

You can manually set the age in the script or use $4 in the policy.

Set the profile paths you don't want deleted. You can add more if needed.

#!/bin/bash
AGE=## # Delete /Users/ folders inactive longer than this many days

# CHECK TO SEE IF A VALUE WAS PASSED IN PARAMETER 4 AND, IF SO, ASSIGN TO "AGE"
if [ "$4" != "" ]; then
  AGE=$4
fi

KEEP=("/Users/user1" "/Users/user2" "/Users/user3")
#--End variables--


### Delete Inactive Users ###
if [[ ${UID} -ne 0 ]]; then
  echo "$0 must be run as root."
  exit 1
fi

USERLIST=$(/usr/bin/find /Users -type d -maxdepth 1 -mindepth 1 -not -name "." -mtime +"${AGE}")

echo "Performing inactive user cleanup"

for a in ${USERLIST}; do
  if ! [[ ${KEEP[*]} =~ "$a" ]]; then
    echo "Deleting inactive (over ${AGE} days) account and home directory: $a"

    # delete user
    /usr/bin/dscl . delete "$a" > /dev/null 2>&1

    # delete home folder
    /bin/rm -r "$a"
    continue
  else
    echo "SKIPPING $a"
  fi
done

echo "Cleanup complete"
exit 0

 

pfotenhauer
New Contributor II

What do I have to specify so that the accounts are deleted after logging out? Or what happens if I set $4 to 0?

Thanks in Advance
Robert