我遇到以下代码的问题
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
}
此代码提供以下输出
Timer fired for: baz
Timer fired for: baz
Timer fired for: baz
但我想拥有它foo,bar和baz。问题似乎是$ ex变量最终被所有Timers读取,所以无论它有什么价值,它们都得到它。如何在$ taction中复制$ ex的值以使其唯一?
答案 0 :(得分:2)
尝试使用[scriptblock]::Create()
,在创建时评估参数:
foreach ($ex in ("foo", "bar", "baz"))
{
$timer = New-Object Timers.timer
$taction = [scriptblock]::create("Write-Host Timer fired for: $ex")
$timer.Interval = 1000
$timer.AutoReset = $false
$timer.Start()
Register-ObjectEvent -InputObject $timer -EventName elapsed -SourceIdentifier $ex -Action $taction
}