Reputation: 3509
I have a list of objects and want to filter all elements whose name is like one of the strings in a list.
My current approach is to use where-object
, but this results in a long chain of calls to where-object.
Get-AppxPackage |
where-object {$_.name -notlike "*store*"} |
where-object {$_.name -notlike "*MSPaint*"} ...
I would like to reduce the boilerplate needed here as I expect the list of strings to get quite large.
I would further like to be able to use the filter on another output, which seems I am currently only able to do by copy pasting the where-object block.
Upvotes: 4
Views: 22462
Reputation: 4253
this code shows how to filter using -and and -or in the where-object
class cCustomField
{
[string] $Id
[string] $Name
[string] $Description
[string] $Type
[bool] $On_projects
[bool] $On_people
}
$list = New-Object Collections.Generic.List[cCustomField]
... load your data ....
filter using -and -or
$my_object=$list | Where-Object {$_.name -EQ 'gender' -and $_.on_people -EQ $true }
Upvotes: 0
Reputation: 61218
You can use regex notmatch
instead. This will be a lot faster to execute.
Something like
Get-AppxPackage | Where-Object {$_.name -notmatch 'store|MSPaint'}
Instead of typing in the literal names to not match, you can build the pattern from an array or by reading in a textfile. Lets say you have a list of names in a textfile
store
MSPaint
...
You can then read in this file as array with
$list = Get-Content -Path "<PATH TO THE FILE>"
Next combine this list to build the pattern like
$pattern = (($list | ForEach-Object {[regex]::Escape($_)}) –join "|")
and do
Get-AppxPackage | Where-Object {$_.name -notmatch $pattern}
Hope this helps
Upvotes: 9