Action linked to Timer object not getting executed(Powershell 3)

In the script below an Action(update and print count every timer update) is linked to Timer object , but the Action is not getting executed.

What’s missing?

Console Output- ``` 12-08-2020 21:31:06 Loop Start

Id Name PSJobTypeName State HasMoreData Location Command


8 Timer.Elapsed NotStarted False …

Script-

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

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


$n = 0 

Write-Output $((Get-Date).ToString() + " Loop Start")

$action = {

    if ($n -le 3){

    $n = $n +1
    Write-Output $n
        }else
    {
    Write-Output $((Get-Date).ToString(), "Loop End")
    $Timer.Autoreset = $False
        } 
}

Register-ObjectEvent @objectEventArgs -Action $action

Unregister-Event  -SourceIdentifier 'Timer.Elapsed'
```




$n is out side the action context so inside the the if condition it will always be $null. How are you making sure actions is not executed ? You can try creating temp files in both if and else condition and see which part is executing.

Write-Output in if-else action blocks ensures if the action is getting executed.

Also , tried setting $n to global and script scopes but there is still no output.

Replaced Write-Output in the Action Block with Write-Host and the issue was resolved.

Write-Output pipes the output down a cmdlet and doesn’t write to the Console .

Inorder to write to the Console, Write-Host has to be used.