Delete User on Mac

New Contributor II

I need to delete a local account on a group of Macs. What's the best way to accomplish this? Is there a script I can setup in a policy?

Thanks in advance.


Contributor II

not sure where I heard it but this line below will remove an account and all other references to it cleanly:

sysadminctl -deleteUser **USERNAME**

you will of course need to put this into a policy etc to run as root

Contributor III
  1. Create a new Policy
  2. Select "Local Accounts"
  3. Select "Delete"
  4. Enter the short name of the user to delete
  5. Select to "Permanently delete home directory"

New Contributor II

Thank you both for the quick response. I was able to follow @jason.bracy suggestion.

New Contributor III

This works for a single known user. Is there a way to delete all my students local accounts/home folders, keeping my Admin in tact and without a full wipe of the machine?


Valued Contributor

You can use a for loop.
First up find the list of users

Accounts=$(ls -l /Users | /usr/bin/awk '{print $9}' | /usr/bin/grep -viE '(shared|admin|administrator)')

This will put the account names in the list, and ignore the ones in the end section. Note that the administrator is not really required as the admin will find it.
If you put this into terminal, you will see the results...

ls -l /Users | /usr/bin/awk '{print $9}' | /usr/bin/grep -viE '(shared|admin|administrator)'

Adjust the names in the brackets as you require just put | between each one as a separator.

Then simply use this as the array in a for loop

if [ -z "$Accounts" ]
        # Null result
        echo "Null result for More accounts"
        # Something there, cycle through them and clean
        echo "Found More Accounts, Removing them"
        # search through the local accounts
        for eachaccount in $Accounts
               # Delete files here using $eachaccount
                # Remove the Homefolder
        rm -Rf /Users/“$eachaccount”
                # Remove the account
                sysadminctl -deleteUser “$eachaccount”

Please test and test again before deploying this. It is not a production script from my collection. I have simply put it together for this example.
I do however use a similar, albeit more complicated version, here.
The ls -l command will list all files and folders in the /Users folder, hence shared being in my list. You may also find it pulls in things like .DS_Store .localized and you have to add them in too.