5

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.

2
  • 1
    where-object {$_.name -notlike "store" -and $_.name -notlike "MSPaint" } should work Commented Sep 3, 2018 at 15:14
  • That is slightly better, but it still requires me to copy/paste that where-object construct if I want to filter another output with it. Commented Sep 3, 2018 at 15:25

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

Comments

0

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  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.