计时器对象不启动并执行操作块 (Powershell 3)

Timer object doesn't start and execute Action block (Powershell 3)

在下面的脚本中,Action 链接到 Timer 对象,但即使 Timer 已过(2000 毫秒),Action 也不会执行。

缺少什么?

***Console (No Further Output)-***  
14-08-2020 11:38:54 Action reached 
Id  -  Name  - PSJobTypeName  - State  - HasMoreData -  Location -  Command        
         
5 -Timer.Elapsed ----------   NotStarted - False-------------     Write-Output Get-D.....                      



***Script-***   
Get-event | Remove-Event
Get-EventSubscriber | Unregister-Event

$Timer = New-Object System.Timers.Timer
$objectEventArgs = @{
    InputObject = $Timer
    EventName = 'Elapsed'
    SourceIdentifier = 'Timer.Elapsed'
}

$Timer.Interval = 2000
$Timer.Autoreset = $true
$Timer.Enabled = $true



Write-Output $((Get-Date).ToString() + " Action reached")

$global:n = Write-Output $((Get-Date).ToString() + "Action block executed")
$action = { $n } 

Register-ObjectEvent @objectEventArgs -Action $action

$Timer.start() #even calling timer start method doesn't trigger the action
 

将操作块中的 Write-Output 替换为 Write-Host,问题已解决。

Write-Output 通过 cmdlet 将输出通过管道传输并且不写入控制台。

为了写入控制台,必须使用 Write-Host。