Powershell script Where-Object in foreach

20,880

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
Share:
20,880
Gordon Amable
Author by

Gordon Amable

Updated on July 09, 2022

Comments

  • Gordon Amable
    Gordon Amable almost 2 years

    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.

  • Gordon Amable
    Gordon Amable over 8 years
    Thanks for your help ! Sorry of being so noob at PS... But where should I add it exactly ?
  • Dave Sexton
    Dave Sexton over 8 years
    No need to add it, it is it, my code is doing what I think yours intended to do. The only difference is that I left out the Write-Host line.
  • Gordon Amable
    Gordon Amable over 8 years
    Thanks Dave ! I finally understood how it worked ! That's work great ! Thanks for your help.