Powershell script to remove local admin users except listed users

Bill Artemik 1 Reputation point
2022-01-18T15:41:57.703+00:00

I need to create a script that I can run (through a RMM scripting system we use) that will scan a computer, create a list of local admin accounts, then check to see if they are in a pre-defined list (e.g. <> ("Administrator" and <> "GoodAdmin" and <> "AnotherGoodAdmin") then delete from group. This is for Windows 10 desktop OS.

Ideally we would like to be able to have that "good admin" list be a variable we can get from our RMM software (the system we user lets us package the script into a component with coder defined variables (e.g GoodAdminList) so we can use this with multiple clients.

I envision something like:
$GoodList = $Env:GoodAdminList
$CurrentAdmins = Get-ListOfLocalAdmins (I don't know the actual commands so just bear with the example for the premise)
For each i in $CurrentAdmins
(if i not in $GoodList then delete i
next

Something like that is what I"m looking to accomplish. Is this a difficult process?

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2022-01-18T19:34:43.667+00:00

    If you plan on running the script LOCALLY then this should work (assuming you're looking to clean up the local Administrators group):

    $GroupName = "Administrators"  
    $GoodList = \\ShareName\GoodList.txt  
    $GoodAdmins = Get-Content $Goodlist  
      
    Get-LocalGroupMember $GroupName |  
        ForEach-Object{  
            if ($_.ObjectClass -eq 'User'){  
                if ($GoodAdmins -contains $_.Name){     # ignore groups in the administrators group  
                }  
                else{  
                    Remove-LocalGroupMember -Group $GroupName -Member $_.Name -WHATIF  
                }  
            }  
        }  
    

    Remove the "-WHATIF" when you're satisfied the script isn't removing something it shouldn't be!

    If you're going to be doing this on remote machines you can make the script into a script block and use Invoke-Command.

    EDIT: Removed the "Continue" -- that only works when it's not working with pipelined data.


  2. Alex G 1 Reputation point
    2022-12-07T16:57:41.763+00:00

    Hi, i try both methods:
    LocalAdmin1,LocalAdmin1 and
    LocalAdmin1
    LocalAdmin2

    and also
    LocalAdmin1, LocalAdmin1, LocalAdmin1

    but script removes every account.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.