Foreach Loop

This topic contains 3 replies, has 2 voices, and was last updated by  TommyQuality 5 months ago.

  • Author
    Posts
  • #70631

    TommyQuality
    Participant

    Hi,

    I'm really new to Pester, so I'm probably doing it the wrong way, but Im trying to return $true if services are running. Is this the correct way to do, as im getting a failed test.

     It 'Services running'{
    
           foreach ($Svr in $Svrs){
                $Service = Get-Service -ComputerName $Svr | where Name -Like "*ServiceName*"
                     if ($Service.Status -eq "Running"){
                     return $true
                   }      
    
           } 
                    
        } | Should be $true
    

    Cheers

    TommyQ

  • #70633

    TommyQuality
    Participant

    I've worked this out now. by using

     $Service.Status | should be running

    But now is there a way to report that the service on each server is running, rather tham just showing the single output? Or do i need to write more IT statements?

    Cheers

  • #70687

    Adam Bertram
    Moderator

    Here's how I'd approach this:

    describe 'Services' {
    
        $services = 'foo','bar,'etc'
        $expectedServiceState = 'Running'
    
        $services = Get-Service -ComputerName $Svr -Name $services | where { $_.Status -ne $expectedServiceState }
    
        It 'all expected services are running on the server'{
    
            $services | should benullorempty
        }
    }

    This way is more explicit and easier to understand what you're testing. It also moves your actual assertions into the it block which now allows you to perform multiple assertions on the services in other it blocks.

    If you want more granular output for each service you could do this:

    describe 'Services' {
    
        $services = 'foo','bar,'etc'
        $expectedServiceState = 'Running'
    
        $services = Get-Service -ComputerName $Svr -Name $services
        
        foreach ($service in $services) {
            it "the [$service] service should be running" {
                $service.Status | should be $expectedServiceState
            }
        }
    }
  • #70688

    TommyQuality
    Participant

    That's perfect, thanks Adam.

    Tom

You must be logged in to reply to this topic.