Foreach Loop

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

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

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
        }
    }
}

That’s perfect, thanks Adam.

Tom