I’m having a problem with the following code
foreach ($ex in ("foo", "bar", "baz")) {
$timer = New-Object Timers.timer
$taction = {
Write-Host "Timer fired for: $ex"
}
$timer.Interval = 1000
$timer.AutoReset = $false
$timer.Start()
Register-ObjectEvent -InputObject $timer -EventName elapsed -SourceIdentifier "$ex" -Action $taction
}
This code gives the following output
Timer fired for: baz
Timer fired for: baz
Timer fired for: baz
But I would want to have it foo, bar and baz. The problem seems to be that the $ex variable is read in the end by all Timers so whatever value it has, they all get it. How do I copy the value of $ex in the $taction so that it is unique?
Try using
[scriptblock]::Create(), this evaluate arguments at the creation: