Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell script Where-Object in foreach

Having trouble with my loop:

   $array =@();
    foreach($list in $Lists | Where-Object{"History", "Historic" -notmatch $list.Title}) 
    {
        $result = new-object psobject
        $result | Add-Member -MemberType noteproperty -Name Title -value $list.Title
        $array += $result
        Write-Host $list.Title
    }

I want to save only the results which don't contain "History" or "Historic" in their title.

For example "Workflow blablabla - Historic" wouldn't be saved.

Can't find the right syntax of my condition: returns all results or nothing at all.

like image 207
Gordon Amable Avatar asked Sep 01 '26 22:09

Gordon Amable


1 Answers

Try this:

$result = $lists | ? {$_.Title -notmatch 'Histor(y|ic)'} | Select Title

Your where clause is a regex with a regex on the right-hand side of the -notmatch.

This would also work:

$result = $lists | ? {$_.Title -notmatch 'History' -or $_.Title -notmatch 'Historic'} | Select Title
like image 141
Dave Sexton Avatar answered Sep 04 '26 09:09

Dave Sexton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!