I was recently asked to write a script to track the addition and removal of users from a select number of Active Directory groups. Without resorting to a 3rd party solution, I was able to come up with the following, which logs the members of each group to a simple text file and compares today’s list of group members to the previous day’s export.
This script was configured as a scheduled task, to run once per day. Fill in the action section with whatever you want to do with the data (email, log somewhere, etc).
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 |
# Location to save log files to. DO NOT put a trailing back slash in here $folderpath = "d:\temp\kamal"; # Define the group name prefix (we will find all groups with this prefix - make sure to include at least one asterisk, or this will fail) $groupnameprefix = "aAdmin_*"; # Get all groups matching a specific prefix $groups = get-adgroup -filter {name -like $groupnameprefix}; # Format todays date to be appended to the output file name $today = (get-date).tostring("yyyyMMdd"); # Loop through each group found foreach ($group in $groups) { # Get the most recent export of group members (may or may not be yesterday - just most recent) $previousfileobject = get-childitem $folderpath | where {$_.name -like ("*" + $group.name + "*")} | sort lastwritetime -desc | select -first 1; $previousgroupmembers = import-csv $previousfileobject.fullname; # Get current group members from Active Directory $currentgroupmembers = $group | get-adgroupmember | select samaccountname; # Compare both lists to find new members and removed members $newmembers = compare-object $currentgroupmembers $previousgroupmembers -property samaccountname | where {$_.sideindicator -eq "<="} | select samaccountname; $removedmembers = compare-object $currentgroupmembers $previousgroupmembers -property samaccountname | where {$_.sideindicator -eq "=>"} | select samaccountname; #----------------[ Do something with the the lists of new and removed users here ]---------------- # Save current members to new file $newfilepath = $folderpath + "\" + $today + "_" + $group.name + ".txt"; $currentgroupmembers | export-csv $newfilepath; } |