从另一个 PowerShell 运行空间管理对象和变量

manage objects and variables from another PowerShell runspace

我目前正在 Powershell 中使用 System.Timers.Timer 对象。

我遇到的问题是,当您注册到 "Elapsed" 活动时

Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier ThirtySecTimer -Action $scriptblock

脚本块将 运行 在不同的 Powershell 运行空间/线程中 这里的问题是,我想修改脚本块中的计时器对象并基本上创建一个更短间隔的循环,直到达到 x 秒并且脚本停止

$action={
    $timer.stop()
    Show-MsgBox -Prompt "time's up" #selfdefined function using Windows Forms
    $timer.interval=$interval - 1000
    $timer.start()
}

我找到了定义 运行spaces 的选项,但我不确定是否可以通过自定义 运行spaces 使用计时器对象。另外我认为使用 运行spaces 对于这个任务来说有点过头了。

是否有另一种(更简单的)方法来让它工作? 如果不是,是否可以通过自定义运行空格来操作定时器对象? (如果我必须使用 运行 空格,我可能会以不同的方式执行此操作,但很高兴知道将来)

$timer 本身作为第一个参数作为 sender 传递给事件处理程序。这会自动填充操作块内的 $Sender 自动变量。

您可以修改该对象引用而不是直接取消引用 $timer

# Create a timer starting at a 10 second interval
$timer = New-Object System.Timers.Timer
$timer.Interval = 10000

# Register the event handler
Register-ObjectEvent $timer Elapsed timersourceid -Action {
    Write-Host "Event triggered at $(Get-Date|Select-Object -ExpandProperty TimeOfDay)"

    $Sender.Stop()
    if($Sender.Interval -ge 1000)
    {
        $Sender.Interval = $Sender.Interval - 1000
        $Sender.Start()
    }
    else
    {
        Write-Host "Timer stopped"
    }
}

您还可以通过在 Action 脚本块中定义一个参数块来覆盖变量名称,第一个参数始终是发送者,第二个参数是 EventArgs(相当于 $EventArgs 自动变量):

Register-ObjectEvent $Timer Elapsed SourceId -Action {
    param($s,$e)

    $s.Stop()
    Write-Host "Event was raised at $($e.SignalTime)"
}