by oising
16. May 2007 23:02
I've included some handy wrapper functions to make working with events and scriptblocks a bit easier - download the example script called "event handling wrapper functions" from the Releases page.
- Add-EventHandler : Automatically run a scriptblock when the provided event occurs on a given variable (when inside Do-Events loop)
- Add-EventHandler [-Variable] <PSVariable> [-EventName] <String> [-Script] <ScriptBlock>
- Remove-EventHandler : Remove all bindings for the specific event from the given variable.
- Remove-EventHandler [-Variable] <PSVariable> [-EventName] <String>
- Do-Events : Much like VB's DoEvents command, this function puts PowerShell into a waiting state and will call your ScriptBlocks when your configured events occur. Use Ctrl+C to exit.
- Do-Events [-ExitImmediately] <Boolean>
NOTE: your ScriptBlocks will only be called if you're inside a Do-Events loop.
1# Add-PSSnapin PSEventing
2# $fsw = new-object system.io.filesystemwatcher
3# $fsw.Path = "c:\temp"
4# $fsw.EnableRaisingEvents = $true
5# Add-EventHandler (get-variable fsw) deleted {
param([System.Management.Automation.PSVariable]$variable, [EventArgs]$args)
... do stuff ... }
6# Do-Events $false
an example how to wire up an event using the wrapper scripts