Author Posts

October 29, 2015 at 7:37 am

I am trying to get a permanent event hander to work – so far I fail.

I have two basic scripts – one that sets the handler and another one that is meant to run when the event occurs.

Here is the core of the event-handler :

# Group to monitor
$Group = 'UG-GAdmin'

#region Create the Event Filter
# Create the Event Filter
Write-Verbose -Message "*** Creating the Filter to Monitor Group $Group"            
$Q = "Select * FROM __InstanceModificationEvent `
      WITHIN 5 `
     WHERE TargetInstance ISA 'ds_group' AND TargetInstance.ds_name = '$Group'"
# Set parameters to call to New-CimInstance
$param = @{
           QueryLanguage =  'WQL'
           Query          =  $Q
           Name           =  "EventFilter1"
           EventNameSpace =  "root/directory/LDAP"
       }
# Now create the Instance Filter
   $InstanceFilter = New-CimInstance -ClassName __EventFilter -Namespace root/subscription -Property $param -Verbose 
#endregion  
#region Create the Permanent Event Consumer details
$param =@{
          Name = "EventConsumer1"
          CommandLineTemplate="PowerShell.exe -File C:\test.ps1 -Group $group"
       }

$InstanceConsumer = New-CimInstance -Namespace root/subscription -ClassName CommandLineEventConsumer -Property $param -Verbose

#endregion 
#region create a binding between the Filter Filter and the consumer
$param = @{
          Filter = [ref]$InstanceFilter     
           Consumer=[ref]$InstanceConsumer
         }

$InstanceBinding= New-CimInstance -Namespace root/subscription -ClassName __FilterToConsumerBinding  -Property $param -Verbose 

#endregion 

The monitor.ps1 looks like this:

PARAM([string]$Group)
# Add header, details and trailer to the file
Add-Content -Path  C:\foo\cim\wmi.log  -Value '**********'
Add-Content  -Path  C:\foo\cim\wmi.log  -Value "$(get-date) monitor.ps1 detected change in group: [$Group]" 
Add-Content  -Path  C:\foo\cim\wmi.log  -Value '**********'

If I then add a user to the group I get no updated wmi.log file.

Clues?

December 28, 2015 at 11:28 am

What I remember from using permanent event subscribers in the past, they don't play well with PowerShell, you need to wrap the call in vbs and call with cscript.

Edit: more info: http://blog.pluralsight.com/monitor-folders-with-wmi-event-subscriptions

December 29, 2015 at 1:21 am

Fortunately, Daniel, your memory is poor – WMI events do indeed play well with WMI and WMI plays well with PowerShell.

If you look at http://www.dexterposh.com/2014/01/powershell-monitor-ad-group-membership.html you will see an example of what I am trying to do.