In PowerShell you can subscribe to an event by using the add_NameOfEvent({scriptblock})
-method of the object. This works well for Form objects like buttons etc. However when I tried it with a System.Timers.Timer
it didn't work. Why is that? Sample:
$timer1 = New-Object System.Timers.Timer
$timer1.Interval = 2000
$timer1.add_Elapsed({ Write-Host "Timer1 tick" })
$timer2 = New-Object System.Timers.Timer
$timer2.Interval = 2000
Register-ObjectEvent -InputObject $timer2 -EventName Elapsed -Action { Write-Host "Timer2 tick" }
$timer1.Start()
$timer2.Start()
$timer2
will work fine, but $timer1
will never write to the console. What makes a Timer
different from ex. a form-component(where the add_...
method works)? Does the Timer
run in a seperate thread and because of that, writes to a "hidden" console?
Proof that the method works with form-components for those not familiar with it:
PS > Add-Type -AssemblyName System.Windows.Forms
PS > $b = New-Object System.Windows.Forms.Button
PS > $b.add_click({ Write-Host "button" })
#Get-EventSubscriber won't show this event, but it's added
PS > $b.PerformClick()
button