Skip to content

Instantly share code, notes, and snippets.

@roundand
Created June 13, 2014 14:29
Show Gist options
  • Save roundand/2ed01e7feb3a90119f4a to your computer and use it in GitHub Desktop.
Save roundand/2ed01e7feb3a90119f4a to your computer and use it in GitHub Desktop.
Demonstration of Async Event processing in PowerShell v2
# Illustration (based on concepts in http://blogs.technet.com/b/heyscriptingguy/archive/2011/06/16/use-asynchronous-event-handling-in-powershell.aspx
# and code nicked from an answer in http://social.technet.microsoft.com/Forums/en-US/96b339e2-e9da-4802-a66d-be619aeb21ac/execute-function-one-time-in-every-10-mins-in-windows-powershell
# )
#####
#
# PASTE LINES BELOW INTO CONSOLE
#
#
## Create an Timer instance
$timer = New-Object Timers.Timer
## Now setup the Timer instance to fire events
$timer.Interval = 2000 # fire every 2s
$timer.AutoReset = $false # do not enable the event again after its been fired
$timer.Enabled = $true
# register your event
Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier Chatty -Action {Write-Host "Chatty"}
# view event subscriptions
get-eventsubscriber
# now start the timer
$timer.Start()
# go wild
$timer.AutoReset = $true
# help!!!!
$timer.AutoReset = $false
#
# Up-arrow on the console to $true to keep event firing, or to $false to stop the event.
#
# Repeat at will :)
#
#
#
# END PASTE BLOCK
#
#####
## let's drop this event
Unregister-Event Chatty
get-eventsubscriber
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment