Question

I would like to know how to filter the collection $view using a predicate filter. I have seen numerous examples of a predicate filter in C# but not many for PowerShell. It would be great to see a working example in PowerShell.

Basically when I set the filter variable to a string and refresh $view, the collection should filter to show me just the rows or objects that matched the filter. If the filter is empty the entire collection of objects should be shown.

I think this should work in the console without using any forms but i haven't been able to create a filter of the type (system.predicate) in PowerShell.

$a = New-Object System.Collections.ObjectModel.ObservableCollection[object]   
    $svcs = gsv -ComputerName LocalHost | 
                        select @{n="Server";e={$_.machinename}},Name,Displayname,status 

    $svcs | ForEach {
        $a.Add((
            New-Object PSObject -Property @{
                Server = $_.server
                Name = $_.name
                Displayname = $_.displayname
                Status = $_.status
            }
        ))      
    }   


    $view = [System.Windows.Data.CollectionViewSource]::GetDefaultView($a)
    $filter = "bits"
    $view.Filter = "Predicate FIlter???"
    $view.Refresh()
Was it helpful?

Solution

Just pass a script block which takes a single parameter. The script block should return true for items which you want to include in the view and false for those that you do not want to include. The following works for me on PowerShell v4:

$view = [System.Windows.Data.CollectionViewSource]::GetDefaultView($a)
Write-Host "Setting filter to 'vss'"
$filter = "vss"
$view.Filter = {param ($item) $item -match $filter}
$view.Refresh()
$view
Write-Host "Setting filter to 'BITS'"
$filter = "BITS"
$view.Refresh()
$view

EDIT: Adding the output printed on a test computer of mine

Running the above script on a test computer resulted in the following output:

Setting filter to 'vss'

                  Status Server                   Name                     Displayname            
                  ------ ------                   ----                     -----------            
                 Running LocalHost                SQLWriter                SQL Server VSS Writer  
                 Stopped LocalHost                vmicvss                  Hyper-V Volume Shado...
                 Stopped LocalHost                VSS                      Volume Shadow Copy     
Setting filter to 'BITS'
                 Running LocalHost                BITS                     Background Intellige...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top