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

This topic contains 4 replies, has 3 voices, and was last updated by  Simon Wåhlin 3 years, 8 months ago.

  • Author
  • #20206



    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

    Rob Simmers

    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


    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

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

    Rob Simmers

    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

    Simon Wåhlin

    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:

       # 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.