Last active
November 10, 2023 13:32
-
-
Save jdhitsolutions/845b4f84117f6145cdda1babe2d81298 to your computer and use it in GitHub Desktop.
PowerShell code to watch for Active Directory Events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| This is old code that still works in Windows PowerShell | |
| as a temporary event subscriber for Active Directory events. | |
| #> | |
| Function Get-WmiADEvent { | |
| Param([string]$query) | |
| $path="root\directory\ldap" | |
| $EventQuery = New-Object System.Management.WQLEventQuery $query | |
| $scope = New-Object System.Management.ManagementScope $path | |
| $watcher = New-Object System.Management.ManagementEventWatcher $scope,$EventQuery | |
| $options = New-Object System.Management.EventWatcherOptions | |
| $options.TimeOut = [timespan]"0.0:0:1" | |
| $watcher.Options = $options | |
| cls | |
| Write-Host ("Waiting for events in response to: {0}" -F $EventQuery.querystring) -backgroundcolor cyan -foregroundcolor black | |
| $watcher.Start() | |
| while ($true) { | |
| trap [System.Management.ManagementException] {continue} | |
| $evt=$watcher.WaitForNextEvent() | |
| if ($evt) { | |
| $evt.TargetInstance | select * | |
| Clear-Variable evt | |
| } | |
| } | |
| } | |
| #Sample usage | |
| # $query="Select * from __InstanceCreationEvent Within 10 where TargetInstance ISA 'DS_USER'" | |
| # $query="Select * from __InstanceCreationEvent Within 10 where TargetInstance ISA 'DS_GROUP'" | |
| # $query="Select * from __InstanceModificationEvent Within 10 where TargetInstance ISA 'DS_USER'" | |
| # $query="Select * from __InstanceModificationEvent Within 10 where TargetInstance ISA 'DS_COMPUTER'" | |
| # | |
| # Get-WmiADEvent $query |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment