I want to write to console from an asynchronus event in powershell.
$timer = New-Object Timers.Timer
$timer.Interval = 2000
$timer.AutoReset = $false
$timer.Enabled = $true
Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier c4n4 -Action {Write-Host test}
This obviously works. But if i encapsulate the Write-Host action within a function. It doesnt anymore.
function myFunc{
Write-Host test
}
$timer = New-Object Timers.Timer
$timer.Interval = 2000
$timer.AutoReset = $false
$timer.Enabled = $true
Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier c4n4 -Action {myFunc}
So basically my question is. How do i write to console from an event within a function?
You need to declare the function in the global scope: