Windows.Forms.Timer scope

Viewed 39
$timer = [Windows.Forms.Timer]::new()
$timer.Interval = 1000
$b=5
function tick {
    write-host ($b++)
}
$timer.add_tick({ tick })

$Form = [Windows.Forms.Form]::new()

$Timer.Start()
$Form.Showdialog()

Output always 5. How to make timer be able to see vars from global scope?

1 Answers

You could use the script scope modifier

$timer = [Windows.Forms.Timer]::new()
$timer.Interval = 1000
$script:b=5
function tick {
    write-host ($script:b++)
}
$timer.add_tick({ tick })

$Form = [Windows.Forms.Form]::new()

$Timer.Start()
$Form.Showdialog()

More information can be found here about_scopes

Related