2020 | Scott W. Head  |  Sr. Systems Admin | Certified Microsoft Windows Server Administrator

PowerShell Remove from Local Admin

    <#  
    .SYNOPSIS
        Uses Source File - Goes to remote systems and removes account from Local Administrators group
    
    .DESCRIPTION
        Use this for compliance to remove accounts from the local admin group when needed
    
    .NOTES          
          Requires Rights on Machines   
          Author: Scott Head

        ======================================
        CSV Format:

        Server            Account
        ServerNameHere    AccountoRemove1
        ServerNameHere    AccountoRemove2
        ServerNameHere    AccountoRemove3

        ======================================
#>

#Command to be Executed 
$MyCommand={        

            
            Param($Var)
            $Admins=$Var          

            $Group = [ADSI]("WinNT://$Env:Computername/Administrators,group") 
            $Group.Members() | 
            foreach { 
            $AdsPath = $_.GetType().InvokeMember('Adspath', 'GetProperty', $null, $_, $null) 
            $A = $AdsPath.split('/',[StringSplitOptions]::RemoveEmptyEntries) 
            $Names = $a[-1]  
            $Domain = $a[-2] 
 
            #Gets the list of users to be removed from a TXT that you specify and checks if theres a match in the local group 
            foreach ($name in $names) { 
            Write-Output "Verifying the local admin user $Name on computer $Env:Computername"            

           
            foreach ($Admin in $Admins) { 

            if ($name -eq $Admin) { 
 
            #If it finds a match it will notify you and then remove the user from the local administrators group 
            Write-Output "User $Admin found on computer $Env:Computername ... " 
            $Group.Remove("WinNT://$Env:Computername/$domain/$name") 
            Write-Output "$Name - Removed" }}}} 
            
}

#Gets Input File of Accounts and Comptuer Names 
$Inputdata=Import-CSV C:\Temp\Remove_LocalAccount_Template.csv

#Loops through records in file
 Foreach($Machine in $InputData){  
    #Assigned Machine account to Invoke and passes the Account to be removed   
    Invoke-Command $Machine.Server -Scriptblock $MyCommand -ArgumentList $Machine.Account 
}