Skip to content

Instantly share code, notes, and snippets.

@jdhitsolutions
Last active November 10, 2023 13:32
Show Gist options
  • Select an option

  • Save jdhitsolutions/845b4f84117f6145cdda1babe2d81298 to your computer and use it in GitHub Desktop.

Select an option

Save jdhitsolutions/845b4f84117f6145cdda1babe2d81298 to your computer and use it in GitHub Desktop.
PowerShell code to watch for Active Directory Events
<#
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