Dynamic and interactive filtering in Powershell

Filtering in Powershell are one of the most expressions i’m use for drill down get-cmdlet results. There are so much situations we wouldlike to have some simple and clear technique to see the results in different views.As an Example I will use get-process with three views:

  1. SlowMotion (More about here.) 
  2. Startet Services 
  3. Stopped Services who begins with “VW*”

The most scripts are using one view per File:

    Get-ServicesByStopped.ps1 | Get-ServicesInSlowMotion.ps1

The scripts above are displaying two different views. This will give you very fast a big collection of files.

One other approach is display views over Parameters. Maybe you will use

.\Get-MyProcesses.ps1 –ReportByVMWareStopped

Example 1:

Param(
    [switch] $ReportBySlowMotion, 
    [switch] $ReportByStartet,
    [switch] $ReportByVMWareStopped
)

If($ReportBySlowMotion)
{
    foreach($process in @(Get-service))
    {$process; Start-Sleep -milliseconds 500}
}

if($ReportByStartet)
{Get-service | ?{$_.Status -eq "Startet"}}

if($ReportByVMWareStopped)
{Get-service | ?{$_.Status -eq "Stopped" -and $_.Name -ilike "VM*"}}

Using filters dynamic is getting scripting simple to extend and flexible to use.

Basicly I create a few lines that do the following:

  • First normaly create filters in the Syntax “filter Filter-xxx{…}”. This is the best Advantage because just define the filter und you will get the selection for the filter in your Script.
  • Load the filters when its needed from the Function Provider
  • Display the avaible filters so that the user can choose the right one.
  • Load the definition and show the result as selected.

image0 

Example: Dynamic Filters

## Creating the Filters
filter Filter-VMWare-Stopped{if($_.Status -eq "Stopped" -and $_.Name -ilike "VM*"){$_}}
filter Filter-Startet{if($_.Status -eq "Startet"){$_}}
filter Filter-SlowMotion{$_; Start-Sleep -milliseconds 500}

## Get All Filters by Name (Scoped filters need some Cleanups)
$filterobjects = & get-childitem function: | ?{$_.CommandType -eq 'Filter'}

$filterobjects | ft name

$choosedFilter = read-host "`nChoose your Filter"

## Choose the filter Definition (For the Filter-Stopped it will contain if($_.Status -eq "Stopped"){$_})
$choosedFilterDefinition = (get-item function:$choosedFilter).Definition

## The Where-Object need's a Scriptblock.
$currentFilter = [scriptblock]::Create($choosedFilterDefinition)

get-service | where-object $currentFilter | ft -autosize Name, Status, DisplayName

Hinterlassen Sie einen Kommentar