Output results of powershell command to textbox in real time

Jan 29, 2014 at 6:20 PM
Hello,

I am looking at building a script with a front-end using ShowUI that will query multiple data sources based upon user input and output the results to a textbox. One such command is get-winevent which I am going to filter based on user input and display the results of the command in the text box. What I can't figure out how to do is to get the actual output of the command to display as opposed to the results of the command. Can someone provide some example code on how to do this? I would also like to color code each line in the textbox based upon keywords if that is possible. Thank you and sorry to trouble you.
Coordinator
Feb 4, 2014 at 11:29 PM
Edited Feb 4, 2014 at 11:57 PM
I'm afraid I don't understand what you mean by the difference between output and results. If what you want is the TEXT that PowerShell would display in a console, then you just need to use Out-String to get that. I suggest also using Format-Table -AutoSize because that will make sure none of your text gets cut off ... but it depends on what your command is ;-)

Setting the text of a TextBox couldn't be easier:
stackpanel {
   textbox -name output -FontFamily Consolas -IsReadOnly -MaxHeight 500 -MinHeight 20
   textbox -name command -MinHeight 20 -Text "Get-Service"
   button "Execute" -IsDefault -on_click {
      $output.Text = Invoke-Expression $command.Text | Format-Table -Auto | Out-String -Width 300
   }
} -On_Initialized { $command.Focus() } -Show
Note the use of -IsDefault to make it so that hitting enter in the command box submits it, and the On_initialized event handler to set focus on the command box, these are tiny details that make your apps much more friendly.

You could also use a DataGrid, which binds directly to the objects (this is cool because you keep a copy of them and can do additional things with them, if you want to).
grid -columns *,50 -rows *,Auto {
   datagrid -ColumnSpan 2 -name output -FontFamily Consolas -IsReadOnly -MinHeight 20
   textbox -Row 1 -name command -MinHeight 20 -Text "Get-Service"
   button -Row 1 -Column 1 "Execute" -IsDefault -on_click {
      $output.ItemsSource = Invoke-Expression $command.Text
   }
} -On_Initialized { $command.Focus() } -Show
As for coloring output, you need to use a RichTextBox for that and learn about FlowDocument markup, it's a bit of a pain, and I'll have to write more about that later if you need it ;-)