How do verify all items in list to be certain value?

Welcome Forums General PowerShell Q&A How do verify all items in list to be certain value?

This topic contains 4 replies, has 3 voices, and was last updated by

 
Participant
3 years, 11 months ago.

  • Author
    Posts
  • #20206
    GS

    Participant
    Points: 0
    Rank: Member

    Hello,

    I need to verify that all items returned by Get-WebapзPoolState cmdlet are set to 'Stopped' in do{}while() statement as condition for the loop to keep going.
    Something like Get-WebAppPoolState |?{$_.Value -ne 'Started'} but I need this to return $True or $False based whether there are still any AppPools which are started.
    How do I do that most elegantly? PS is 2.0

  • #20207

    Participant
    Points: 0
    Rank: Member

    I don't know if it's elegant, but you could just do

    $badWebApp = Get-WebAppPoolState |?{$_.Value -ne 'Started'} 
    If ($badWebApp.Count -gt 0) {
        #remediation code here
    }
    else {
        #everything is good...
    }
    
  • #20208
    GS

    Participant
    Points: 0
    Rank: Member

    Well all this shall be on one line since it's inside condition of do()while{} loop
    The best I come up so far like yours is to count number of returned elements

    do
    {
    Start-Sleep 2
    }
    while ((Get-WebAppPoolState | ?{$_.Value -ne 'Started'} | measure).Count -eq 0)
  • #20209

    Participant
    Points: 0
    Rank: Member

    You can cast the count to boolean too if you would prefer. 0 is False and any other number is True:

    [boolean](Get-Service | Where{$_.Status -ne "Running"}).Count
    
  • #20213

    Participant
    Points: 0
    Rank: Member

    We can take it even one step further.

    PowerShell expects a boolean value from the condition and will turn anything returned from the condition to a boolean.
    Since [bool]$array will return true as long as $array is a non-empty array (with a few specific exeptions, but that doesn't really matter in this case) we can do this:

    Do
    {
       # Code to start AppPools
    } While (Get-WebAppPoolState | Where {$_.Value -ne 'Started'})
    

    As long as Get-WebAppPoolState returns any object whose value does not equal 'Started' the loop will continue.

The topic ‘How do verify all items in list to be certain value?’ is closed to new replies.