Use a Grid View Window as a Universal Dialog

by Nov 19, 2015

Out-GridView can be much more than just a window showing results. You can turn it into a pretty useful universal dialog.

Let's assume you want to present to the user a number of running applications, and have him/her choose one to stop. The classic approach would look like this:

Get-Process | 
  Where-Object { $_.MainWindowTitle } |
  Out-GridView -OutputMode Single |
  Stop-Process -WhatIf

When you pipe original objects to Out-GridView, the user would see all the usual object properties. That may be OK, but if you want a better user experience, you can use some sophisticated PowerShell tricks:

#requires -Version 3

$prompt = 'Choose the process you want to terminate:'

Get-Process | 
  Where-Object { $_.MainWindowTitle } |
  ForEach-Object {
    New-Object PSObject -Property @{$prompt = $_ | Add-Member -MemberType ScriptMethod -Name ToString -Force -Value  { '{0} [{1}]' -f $this.Description, $this.Id } -PassThru }
  } |
  Out-GridView -OutputMode Single -Title $prompt |
  Select-Object -ExpandProperty $prompt |
  Stop-Process -WhatIf

Look at the user experience first: the grid view window now looks a lot less confusing to the user. Now let's check out what is needed to create this experience.

Before the results are piped to Out-GridView, they are repackaged in a new object with just a single property. This property carries the name you define in $prompt, so it is basically your message to the user.

When you do this and pipe the wrapped objects to Out-GridView, you would now see the text representation of the object. To control this text representation, the object ToString() method is overwritten with a new function that displays whatever you like. In the example, it displays the process description and process ID.

The process selected by the user is then unwrapped again. This way, you get back the original objects.

Twitter This Tip! ReTweet this Tip!