Problem with a Permanent WMI Event Handler

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 
#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

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

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


The monitor.ps1 looks like this:

# 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.


any clues?

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:

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

If you look at you will see an example of what I am trying to do.