This is Part 1 of 4 (Part 2 is here, Part 3 is here, and Part 4 is here), where I go through how I use PowerShell to audit different aspects of workstations/servers. There are a lot of ways to perform these types of tasks, and a lot of software which can do these things out of the box. SCCM is often used for these sorts of things, but I find a lot of companies haven’t invested in SCCM or spent the time “investing” in SCCM SMEs to make it really useful.
So, I often resort to these types of scripts to get the data I need, and often run these things as Scheduled Tasks, locally, and have the data stored it in a central database (maybe a topic for down the line).
This script gets the Local Computer groups, and the membership of those groups. Usually I’m just interested in the local Administrators group, but this gives you everything. There’s an argument for not reporting back on empty groups – but I’ll leave that up to you to change/implement if you want to skip those.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# Get all local groups $localgroups = net localgroup; # Initialise output object $getmembers = @(); # Loop through each line foreach ($localgroup in $localgroups) { # Only process lines that being with an asterisk (skip the junk) if ($localgroup[0] -eq "*") { $getmemberline = "" | select groupname, members; # Set group name $getmemberline.groupname = $localgroup.substring(1); # Get members of the group $getmemberline.members = net localgroup $getmemberline.groupname | where {$_ -and $_ -notmatch "command completed successfully"} | select -skip 4 # Get count of members to adjust output for groups with only one member $membercount = ($getmemberline.members | measure-object).count; if ($membercount -eq 1) { # Add single group member into an array - otherwise there would be a mix of arrays of strings and simple strings in the output $temparray = @(); $temparray += $getmemberline.members; $getmemberline.members = $temparray; } # Add results to the parent object $getmembers = $getmembers + $getmemberline; } } |
The resulting object, $getmembers. should then look something like this:
Although a few years old now, I wrote this in 2015 which does something similar: https://hkeylocalmachine.com/?p=166