我创建了一个 powershell 计时器,每 1 秒后,我想运行一个函数来执行或发布文本到界面上的文本框日志。
运行下面。当您单击开始时,每 1 秒,日志文本区域应显示“每 1 秒发布一次日志,而不是批量”。但是,当您单击“停止”时,这些消息只会一次性显示为一批。
这个问题网上好像没有答案!
代码:
$global:timer = New-Object System.Timers.Timer
$global:timer.Interval = 1000
function AddToLog($logtext)
{
$txtLog.Text = $txtLog.Text + "`r`n" + $logtext
$txtLog.ScrolltoCaret
}
function startTimer() {
Register-ObjectEvent -InputObject $global:timer -EventName Elapsed -SourceIdentifier theTimer -Action {AddToLog('Post to log every 1 second, not as a batch') }
$global:timer.start()
Write-Host "Start Timer"
}
function stopTimer() {
$global:timer.stop()
Write-Host "Close Function"
Unregister-Event theTimer
}
########################
# Setup User Interface
########################
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objForm = …Run Code Online (Sandbox Code Playgroud)