Powershell for Object-based Selection Prompt

One of its most powerful features of PowerShell is its ability to work with objects, allowing you to manipulate data in a structured and intuitive way.

Today, we’ll explore how to make an object-based user selection menu in PowerShell. Using Out-GridView is an easiest option for this purpose. Also, I make a custom function for the object-based user selection.

Using Out-GridView

Using Out-GrideView is pretty straightforward, you can pipe any objects to Out-GrideView. Here is the screenshot to start any service selected by user.

Get-Service | Out-GridView -Title "Select Any Service to Start" -OutputMode Multiple | Start-Service
Fig-1: You can select single or multiple objects

Using Powershell Custom Function

I wrote a function to select the objects based on IDs which are added as a new column. You can select single or multiple IDs by using comma (,) or dash (-). You can download the script from gist.

Fig-2: Selecting Single Object
Get-Service | select -First 10 | Get-Selection-Objects -ColumnOrder Name,DisplayName,Status

In Fig-2, 10 objects from Get-Service are piped to our function where we select a single object. The output type is the Ps custom object.

In the next example, the selected objects are piped to to Start-Service. To make the selection clearer, we sort the Status column by using -SortBy parameter. See Fig-3.

Get-Service | select -First 10 | Get-Selection-Objects -ColumnOrder Name,DisplayName,Status -SortBy Status -MsgOnPrompt "Select Any Service to Start" | Start-Service
Fig-3: Start Services which user has selected and rerun the script for rechecking

We will stop the selected services now by using Stop-Service. See Fig-4. Note that you can use a combination of commas and dashes for the selection.

Get-Service | select -First 10 | Get-Selection-Objects -ColumnOrder Name,DisplayName,Status -SortBy Status -MsgOnPrompt "Select Any Service to Stop" | Stop-Service
Fig-4: Stop 6 Services and Recheck

Here is the explanation of the parameters.

Obj – [PsObject[]] Array of objects to be processed.
HideMenu– [boolean] Show or hide the table menu prompted to user.
ColumnToHide – [string] Name of the column to hide when displaying to user (eg: PrimaryKeys or Guids).
ColumnOrder – [array] Names of the columns to be displayed in order
SortBy – [array] Names of the columns which will be sorted in ascending order.
MsgBeforePrompt – [string] Message shown to user before the Read-Host prompt.
MsgOnPrompt – [string] Message shown to user with the Read-Host prompt.
MsgAfterPrompt – [string] Message shown to user after the Read-Host prompt.
MsgOnExit – [string] Message shown to user along the exit message when the user selects 0.
IsPrompt – [boolean] Show or hide the Read-Host prompt to user.

Here is the script.

Leave a Reply

Your email address will not be published. Required fields are marked *