Audit Membership of the Local Admins Group with PowerShell

Recently, I needed to make sure that specific accounts were members of the local administrators group on several servers along with making sure that no other users were members of it.

PowerShell version 5.1 introduced a module named Microsoft.PowerShell.LocalAccounts that contains the following commands for managing local users and groups.

Get-Command -Module Microsoft.PowerShell.LocalAccounts

audit-local-groups1a.jpg

Checking the group membership is as easy as running Get-LocalGroupMember within the script block of Invoke-Command and targeting remote systems.

Invoke-Command -ComputerName sql14, sql16, sql17 {
    Get-LocalGroupMember -Group Administrators
}

audit-local-groups2a.jpg

Adding a user to the group is also simple. The commands seem very basic, although they get the job done. I was expecting an Identity parameter and maybe a PassThru parameter, but no such luck.

Invoke-Command -ComputerName sql14, sql16, sql17 {
    Add-LocalGroupMember -Group Administrators -Member mikefrobbins\mike0
}

audit-local-groups3a.jpg

You could also group your output to make it easier to determine who’s on first and what’s on second.

Invoke-Command -ComputerName sql14, sql16, sql17 {
    Get-LocalGroupMember -Group Administrators
} | Sort-Object -Property PSComputerName |
Format-Table -GroupBy PSComputerName

Invoke-Command -ComputerName sql14, sql16, sql17 {
    Get-LocalGroupMember -Group Administrators
} | Sort-Object -Property Name |
Format-Table -GroupBy Name

audit-local-groups4a.jpg

And of course, removing a user is also easy and very similar to adding a user.

Invoke-Command -ComputerName sql14, sql16, sql17 {
    Remove-LocalGroupMember -Group Administrators -Member mikefrobbins\mike0
    Get-LocalGroupMember -Group Administrators
}

audit-local-groups5a.jpg

Another thought is that you could use the Write-SqlTableData and Read-SqlTableData commands that are part of the SQLServer PowerShell module to store this information in a database and compare it later to determine if any group membership changes have been made.

ยต