Add-EventHandler -- What am I doing wrong?

May 28, 2009 at 5:19 PM

I am trying to use the Add-EventHandler function:

$fsw = New-Object system.IO.FileSystemWatcher
$fsw.Path = $pwd
$fsw.EnableRaisingEvents = $true
add-eventhandler fsw changed {Write-Host "Something Happened"}

When I do that, I get the following error:

Object reference not set to an instance of an object.
At :line:28 char:14
+     connect-event <<<<  $variable $eventname

What am I doing wrong?  Feeling kind of dumb right now... sorry.

B

Coordinator
Jul 20, 2009 at 6:53 PM

Hi Brian,

The first parameter in add-eventhandler expects a PSVariable, not a string, so invoke it like this:

add-eventhandler (gv fsw) changed {Write-Host "Something Happened"}

where gv is the alias for get-variable.

Also, you then have to run the do-events function to have it process events. Again, these wrapper functions are just a simple demo of what you can do with pseventing. You have way more control once you learn how to use the individual cmdlets.

-Oisin