【问题标题】:Real Time Data With Powershell GUI使用 Powershell GUI 的实时数据
【发布时间】:2016-01-28 11:33:10
【问题描述】:

我在这里挣扎。

使用Powershell和GUI,如何自动刷新表单上的数据?

以下面的脚本为例,如何用我的电脑执行的进程数自动更新标签?

Add-Type -AssemblyName System.Windows.Forms
$Form = New-Object system.Windows.Forms.Form
$Form.Text = "Sample Form"
$Label = New-Object System.Windows.Forms.Label
$Label.Text = "Number of process executed on my computer"
$Label.AutoSize = $True
$Form.Controls.Add($Label)
$Form.ShowDialog()

【问题讨论】:

    标签: powershell powershell-2.0 powershell-3.0 powershell-4.0 powershell-ise


    【解决方案1】:

    您需要在表单中添加一个计时器来为您进行更新。然后将收集进程计数所需的代码添加到 .Add_Tick 中,如下所示:

    function UpdateProcCount($Label)
    {
        $Label.Text = "Number of processes running on my computer: " + (Get-Process | measure).Count
    }
    
    $Form = New-Object System.Windows.Forms.Form
    $timer = New-Object System.Windows.Forms.Timer
    $timer.Interval = 1000
    $timer.Add_Tick({UpdateProcCount $Label})
    $timer.Enabled = $True
    $Form.Text = "Sample Form"
    $Label = New-Object System.Windows.Forms.Label
    $Label.Text = "Number of process executed on my computer"
    $Label.AutoSize = $True
    $Form.Controls.Add($Label)
    $Form.ShowDialog()
    

    【讨论】:

    • 请添加(至少)关于定时器的简短评论,对于未经训练的人来说可能并不明显
    • 感谢 Mathias,添加了一些关于计时器及其 Tick 事件处理程序的描述。
    • 非常感谢埃里克!我还有一个问题。如果我想要第二个标签显示例如 CPU 使用率的百分比,我如何在一个函数调用中更新两个标签?
    • 使用上面的示例,只需创建另一个变量,例如 $labelCPU,然后像第一个标签一样将其添加到表单中。然后更新函数 UpdateProceCount 以更新两个 label.Text 属性。除了说您需要将两个标签对象作为参数传递给函数,以及更新每个属性的单独语句之外,我将把获取 CPU 利用率所需的 powershell 作为练习。
    • 嘿,Eric,我在标签上的鼠标事件上调用了一个函数,但由于我添加了计时器,这些事件不再起作用。我在这里发布了这个:stackoverflow.com/q/33577527/5498995 多一点帮助会很好:)
    猜你喜欢
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    相关资源
    最近更新 更多