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.
1Get-Command -Module Microsoft.PowerShell.LocalAccounts
Checking the group membership is as easy as running Get-LocalGroupMember within the script block of Invoke-Command and targeting remote systems.
1Invoke-Command -ComputerName sql14, sql16, sql17 {
2 Get-LocalGroupMember -Group Administrators
3}
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.
1Invoke-Command -ComputerName sql14, sql16, sql17 {
2 Add-LocalGroupMember -Group Administrators -Member mikefrobbins\mike0
3}
You could also group your output to make it easier to determine who's on first and what's on second.
1Invoke-Command -ComputerName sql14, sql16, sql17 {
2 Get-LocalGroupMember -Group Administrators
3} | Sort-Object -Property PSComputerName |
4Format-Table -GroupBy PSComputerName
5
6Invoke-Command -ComputerName sql14, sql16, sql17 {
7 Get-LocalGroupMember -Group Administrators
8} | Sort-Object -Property Name |
9Format-Table -GroupBy Name
And of course, removing a user is also easy and very similar to adding a user.
1Invoke-Command -ComputerName sql14, sql16, sql17 {
2 Remove-LocalGroupMember -Group Administrators -Member mikefrobbins\mike0
3 Get-LocalGroupMember -Group Administrators
4}
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.
µ