#gets the user GUID based on moving OU's $userguid = Get-Eventlog security -instanceid 4662 | ? {$_.message -like "*%%7685*"} | select @{n='Message';e={$_.ReplacementStrings[6]}} #gets the user DN $usercn = get-adobject $userguid | select -expand distinguishedname #extracts the OU from DN $userou = ([adsi]"LDAP://$usercn").parent -replace "LDAP://" #Shadow groups script to query users in OU then update group membership of that AD group dsquery user "$userou" | dsmod group $usergroup -chmbr
# Finds the most recent event related to a user added to an OU (includes moves)# InstanceID specifies the correct event, 4662 # Message "7685" means "Write Property" # ReplacementStrings[12] distinguishes this event from others since the 'Additional Info' data fields contains user information (and not a dash which this search uses to not select irrelevant results) # Finally the most recent index is selected since this is the event we want to act upon $result = get-eventlog security -instanceid 4662 -message "*%%7685*" | select index,@{n='Message';e={$_.ReplacementStrings[12]}} | ? {$_.Message -ne "-"} | select -expand index -first 1 # Location of file to hold $result value (persistence) $loc = "c:\scripts\ouchangeresult.txt" # Compare most recent result to result in file. If different, continue on with the script if ($result -eq (cat $loc)) { write-host `n"No user OU changes found in Event Viewer Security log--Exiting script"`n -fore green; sleep 1 exit } Else { write "Continuing script" } # Write the new result to a file $result | out-file "$loc"
$shadowgroup = get-adgroup -searchbase "OU=Shadow Groups,OU=Groups,DC=demo,DC=local" -filter {Homepage -like $userou} | select -expand distinguishedname