首页 > 解决方案 > Powershell 显示弹窗并在循环中不断更新弹窗的主体

问题描述

我正在尝试在正文中弹出一些数据以使用 powershell 显示。
虽然,我测试了一些方法来正确地做到这一点。但是在更新弹出消息时,我找不到任何方法来保持循环进度。

请检查下面的消息框。

powershell.png

虽然,我不明白为什么 png 文件没有正确上传。
所以我在下面添加了我的 powershell 代码。

PowerShell 代码如下所示。

$msgBoxTitle = "i value"
$i = 0
while(1){
    $msgBoxBody = "
        current i value is : $i
    "
    $i++;
    [System.Windows.MessageBox]::Show($msgBoxBody, $msgBoxTitle)
}

在这种情况下,我想让循环在循环进行时不会停止并且 msg 框体的值得到更新。

有没有办法做到这一点?谢谢你。

标签: powershellpowershell-3.0messagebox

解决方案


这不是微不足道的,因为(简单地说)PowerShell 不能很好地处理表单。这个答案解释了为什么并给出了如何显示非阻塞表单或消息框的解决方案:

$ps = [PowerShell]::Create()
[void]$ps.AddScript({
    param($Caption, $Text)
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.MessageBox]::Show($Text, $Caption)
})
[void]$ps.AddArgument($msgBoxTitle)
[void]$ps.AddArgument($msgBoxBody)
[void]$ps.BeginInvoke()

但是...... 更新表格会很棘手,我不确定是否有简单的方法来做到这一点。

这个答案提到了showui,一个 PowerShell 模块,但我对此一无所知,对于您的问题来说,这可能是矫枉过正。

在 PowerShell 中显示进度的最佳做法是Write-Progress。对您的代码进行一点更新:

$msgBoxTitle = "i value"
$i = 0
while (1) {
    $msgBoxBody = "current i value is : $i"
    $i++;
    Write-Progress -Activity $msgBoxTitle -Status $msgBoxBody
}

(当然,Write-Progress当您知道操作需要多长时间并且您可以指定百分比时效果最好,因此它将显示一个进度条。但正如您所看到的,它甚至可以在没有它的情况下工作。)


推荐阅读