Write PowerShell Output (as it happens) to WPF UI Control

一世执手 提交于 2019-12-18 09:23:40

问题


I've been reading blogs about writing to the UI from different runspaces (http://learn-powershell.net/2012/10/14/powershell-and-wpf-writing-data-to-a-ui-from-a-different-runspace/).

I'm basically trying to make it so I can click a button in the UI and run a PowerShell script and capture the output of that script as it happens and update the WPF UI control without freezing up the UI.

I've tried a basic example of just writing some output directly, but it seems to hang the UI. I'm using runspaces and dispatcher, but I seem to be stuck on something.

Any ideas?

Thanks.

Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase


$uiHash = [hashtable]::Synchronized(@{})
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open() 
$newRunspace.SessionStateProxy.SetVariable('uiHash',$uiHash)

$psCmd = [PowerShell]::Create().AddScript({
[xml]$xaml = @"
<Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="Window" Title="Patcher" Height="350" Width="525" Topmost="True">
    <Grid>
        <Label Content="A Builds" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="88" RenderTransformOrigin="0.191,0.566"/>
        <ListBox HorizontalAlignment="Left" Height="269" Margin="10,41,0,0" VerticalAlignment="Top" Width="88"/>
        <Label Content="New Build" HorizontalAlignment="Left" Margin="387,10,0,0" VerticalAlignment="Top"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="387,41,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Label Content="B Builds" HorizontalAlignment="Left" Margin="117,10,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.528,-0.672"/>
        <ListBox HorizontalAlignment="Left" Height="269" Margin="103,41,0,0" VerticalAlignment="Top" Width="88"/>
        <Label Content="C Builds" HorizontalAlignment="Left" Margin="185,10,0,0" VerticalAlignment="Top"/>
        <ListBox HorizontalAlignment="Left" Height="269" Margin="196,41,0,0" VerticalAlignment="Top" Width="88"/>
        <Button x:Name="PatchButton" Content="Patch!" HorizontalAlignment="Left" Margin="426,268,0,0" VerticalAlignment="Top" Width="75"/>
        <RichTextBox x:Name="OutputTextBox" HorizontalAlignment="Left" Height="194" Margin="289,69,0,0" VerticalAlignment="Top" Width="218">
            <FlowDocument>
                <Paragraph>
                    <Run Text=""/>
                </Paragraph>
            </FlowDocument>
        </RichTextBox>

    </Grid>
</Window>
"@

$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$uiHash.Window = [Windows.Markup.XamlReader]::Load($reader)

$uiHash.Button = $uiHash.Window.FindName("PatchButton")
$uiHash.OutputTextBox = $uiHash.Window.FindName("OutputTextBox")

$uiHash.OutputTextBox.Dispatcher.Invoke("Render", [Windows.Input.InputEventHandler]    {$uiHash.OutputTextBox.UpdateLayout()}, $null, $null)

$uiHash.Window.ShowDialog() | Out-Null
})
$psCmd.Runspace = $newRunspace
$data = $psCmd.BeginInvoke()

# The next line fails (null-valued expression)
<#
$uiHash.OutputTextBox.Dispatcher.Invoke("Normal", [action]{
    for ($i = 0; $i -lt 10000; $++) {
        $uiHash.OutputTextBox.AppendText("hi")
    }
})#>

回答1:


Out of curiosity, have you considered that instead of PowerShell firing up WPF and displaying some output, it should be the other way around?

Perhaps you should be invoking PowerShell from within a WPF application, and capturing the output to be displayed?

http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C




回答2:


I ran into the same question and seen quiet some suggestions that either refer to C# classes or examples where the UI is placed in the worker instead of the actual worker task. Anyway, after spending quite some time I figured it out:

Add-Type -AssemblyName PresentationFramework
$Xaml = New-Object System.Xml.XmlNodeReader([XML]@"
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Test" WindowStartupLocation = "CenterScreen" ShowInTaskbar = "True">
    <Grid>
        <TextBox x:Name = "TextBox"/>
    </Grid>
</Window>
"@)

Function Start-Worker {
    $TextBox = $Window.FindName("TextBox")
    $SyncHash = [hashtable]::Synchronized(@{Window = $Window; TextBox = $TextBox})
    $Runspace = [runspacefactory]::CreateRunspace()
    $Runspace.ThreadOptions = "ReuseThread"         
    $Runspace.Open()
    $Runspace.SessionStateProxy.SetVariable("SyncHash", $SyncHash)          
    $Worker = [PowerShell]::Create().AddScript({
        for($Progress=1; $Progress -le 10; $Progress++){
            $SyncHash.Window.Dispatcher.Invoke([action]{$SyncHash.TextBox.AppendText($Progress)})
            Start-Sleep 1                                                       # Some background work
        }
    })
    $Worker.Runspace = $Runspace
    $Worker.BeginInvoke()
}

$Window = [Windows.Markup.XamlReader]::Load($Xaml)                              # Requires -STA mode
$Window.Add_Loaded({Start-Worker})
[Void]$Window.ShowDialog()

For a windows control example see: PowerShell: Job Event Action with Form not executed




回答3:


I made some adjustments in your code. I wouldn't run your For loop within the dispatcher and instead would run the dispatcher block in the For loop. I tested and it didn't seem to lock up for me (had some moments where the performance wasn't the best, but that was expected) and kept writing to the window.

for ($i = 0; $i -lt 10000; $i++) {
    $uiHash.OutputTextBox.Dispatcher.Invoke("Normal", [action]{
        $uiHash.OutputTextBox.AppendText("hi")
    })
}



回答4:


This may be a little late but try downloading WPFRunspace , which provides a Powershell backgroundworker cmdlet for WPF and Win Forms GUI scripts that will execute in the background and update your GUI either as output is received or on completion.



来源:https://stackoverflow.com/questions/23142137/write-powershell-output-as-it-happens-to-wpf-ui-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!