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

This topic contains 4 replies, has 3 voices, and was last updated by Profile photo of Simon Wåhlin Simon Wåhlin 2 years, 1 month ago.

  • Author
    Posts
  • #20206
    Profile photo of GS
    GS
    Participant

    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
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    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
    Profile photo of GS
    GS
    Participant

    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
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    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
    Profile photo of Simon Wåhlin
    Simon Wåhlin
    Participant

    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.

You must be logged in to reply to this topic.