For each and where-object

Sara 441 Reputation points
2023-07-06T04:17:39.3033333+00:00

I am trying to add a another where-object condition in the below code, but the syntax fails, what would be the simplest way to achieve that?

foreach ($R in ($VIPResults | Where-Object Status -notmatch "Up|Out Of Service"))

like -and{where-object componentname -match virtualserver}

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2023-07-06T18:07:20.27+00:00

    Like this?

    $VIPResults = [PSCustomObject]@{Status='Up';ComponentName='VP1'},
    [PSCustomObject]@{Status='Out Of Service';ComponentName='VP1'},
    [PSCustomObject]@{Status='Down';ComponentName='VP1'},
    [PSCustomObject]@{Status='Up';ComponentName='VP2'}
    
    $virtualserver = 'VP1'
    foreach ($R in ( $VIPResults | 
                        Where-Object {($_.Status -notmatch "Up|Out Of Service") -AND $_.componentname -eq $virtualserver})){
        $R
    }
    
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Olaf Helper 47,436 Reputation points
    2023-07-06T06:02:42.03+00:00

    When "Status" is a property of the VIPResults, then you have to use $_ as object alias =>

    foreach ($R in ($VIPResults | Where-Object $_.Status -notmatch "Up|Out Of Service"))
    
    

  2. Andreas Baumgarten 123.4K Reputation points MVP Volunteer Moderator
    2023-07-06T12:13:12.28+00:00

    Hi @Sara ,

    it is basically easy to combine two or more where conditions with and and or:

    # Example 1: Two "-and" conditions in one Where-Object
    foreach ($a in 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) { 
        Write-Output $a | Where-Object { $a -gt 2 -and $a -lt 5 }
    }
    
    # Example 2: Two "-and" conditions combined with one "-or" and another two "-and" conditions
    foreach ($a in  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) { 
        Write-Output $a | Where-Object { ($a -gt 2 -and $a -lt 8) -or ($a -gt 10 -and $a -lt 20) }
    }
    # Example 3: Get local computer services with status "Stopped" and Name of service begins with "W"
    Get-Service | Where-Object { $_.Status -eq "Stopped" -and $_.Name -like "W*" }
    
    

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards Andreas Baumgarten

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.