【问题标题】:Redirect output of another PowerShell script to a TextBox on the fly即时将另一个 PowerShell 脚本的输出重定向到 TextBox
【发布时间】:2016-11-30 02:16:07
【问题描述】:

您好,我有一个 ps 脚本,它使用带有 [System.Windows.Controls.TextBox] 的 WPF 显示 GUI。在 GUI 上,我将通过单击各种按钮来调用其他一些 ps 脚本,因此我想将它们的输出即时重定向到 TextBox。

有两件事我无法让它工作:

首先,我尝试使用 cmdlet 来更新 TextBox 的 Text 属性,该方法有效,但仅在 cmdlet 完成之后。所以我需要一种即时更新文本的方法。

接下来我尝试调用其他 ps 脚本,与 cmdlet 不同,我无法捕获它们的输出,即使它们完成后也是如此。我猜是因为这些脚本使用的是Write-Host 而不是Write-Output?否则,我还需要一种方法来捕获 ps 脚本的输出以即时更新文本。

我还认为如果有一个可以添加到 GUI 的 PowerShell cmd 控件会容易得多,所以我不必执行上述操作来实现我想要的。这个控件可以执行 ps 脚本并在那里打印输出,更好的是,读取用户交互输入。如果可能的话,会选择这个作为答案。

【问题讨论】:

    标签: wpf powershell


    【解决方案1】:

    没有示例代码,这有点难以回答。

    通常文本块用于显示文本,文本框用于输入文本,我可能不会对两者使用相同的框。

    如果您想即时更新文本块或框,wpf 有一个计时器,您可以在其中观察变量并将它们放入 UI,如果您的 UI 和逻辑位于不同的线程中,这将特别有用。因此,您可以获取已启动的脚本来更新变量,计时器会监视变量以使其更改并更新 UI。

    Add-Type -AssemblyName windowsbase
    
    $updateBlock = {
    
      $wpftextbox.text = $yourVaribletoWatchGoesHere
    
    }
    
        $timer = new-object System.Windows.Threading.DispatcherTimer
        # Which will fire 100 times every second        
        $timer.Interval = [TimeSpan]"0:0:0.01"
        # And will invoke the $updateBlock            
        $timer.Add_Tick($updateBlock)
        # Now start the timer running            
        $timer.Start()
        if ($timer.IsEnabled)
        {
            Write-Output 'UI timer started'
        }
        else
        {
            $clock.Close()
            Write-Output 'UI update timer did not start'
        }
    

    您是对的,如果他们使用 write-host,他们的输出将难以捕获。您应该编辑脚本,以便它们使用 write-output,而不是 write-host。这是一个很好的例子,说明了为什么这是最佳做法。

    我不确定你所说的 powershell cmd control 是什么意思,但据我所知,这里没有快捷方式。

    【讨论】:

    • 谢谢!但我没有要观察的变量,它是另一个脚本的输出。你有$wpftextbox.text = script.ps #output of another script的例子吗?
    猜你喜欢
    • 2015-09-26
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多