Loop through a collection of items with the Pester TestCases parameter instead of using a foreach loop

One of the huge benefits of attending in-person technology events is getting to network with others. While at the MVP Summit last month I had a chance to demonstrate some of my PowerShell code and Pester tests to Jim Truher. I was developing the code and tests for a session to present for the PowerShell Virtual Chapter of SQL PASS (the code and a video of that presentation can be found here).

In one of my examples, I was looping through a collection of items (computer names of SQL Servers) to run Pester tests against each one using a foreach loop similar to what you'll find in this blog article. Jim wrote the following code (on my computer) to demonstrate how the Pester TestCases parameter could be used to loop through a collection of items without the need for a foreach loop:

1describe a {
2    $cases = @{ one = 1 },@{ one = 1 },@{ one = 1 }
3    it "one is <one> and testing all should be 1" -TestCases $cases {
4        param ( $one )
5        $one | should be 1
6    }
7}

testcases1a.png

He also demonstrated a failing test:

1describe a {
2    $cases = @{ one = 1 },@{ one = 2 },@{ one = 1 }
3    it "one is <one> and testing all should be 1" -TestCases $cases {
4        param ( $one )
5        $one | should be 1
6    }
7}

testcases2a.png

His examples could easily be modified to perform validation of multiple computers (SQL Servers in the following example):

1Describe 'Simple Validation of a SQL Server' {
2    $Servers = @{Server = 'sql011'}, @{Server = 'sql02'}
3    It "The SQL Server Service on <Server> Should Be Running" -TestCases $Servers {
4        param($Server)
5        (Get-Service -ComputerName $Server -Name MSSQLServer).Status |
6        Should Be 'Running'
7    }
8}

testcases3a.png

Thanks to Jim, I now know of a new more efficient way of looping through a collection of items for Pester tests.

µ