PowerShell Pester
Pester is PowerShell's test framework. Describe groups related tests, It is one test, and Should makes an assertion. Invoke-Pester runs them.
Documentation: Microsoft Learn
Overview
The version split matters more than anything else here. Pester 3 shipped with Windows and used a different syntax; Pester 5 is the current version and is not compatible. Code written for 3 fails on 5 in confusing ways, so check with Get-Module Pester -ListAvailable before you copy an example from the internet.
Pester 5 also changed when code runs. Discovery happens first, executing everything outside It blocks to find the tests; then run happens. So variables set at Describe level are not visible the way you expect inside It. Put setup in BeforeAll or BeforeEach, not loose in the Describe body. This single change accounts for most of the confusion when people upgrade.
Mock replaces a command for the duration of a test, which is how you test a function that would otherwise hit Active Directory or delete a file.
Start with the tests that pay for themselves: parameter validation, the edge cases you know are risky, and the bug you just fixed.
Inspect this example’s structure
Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.
$test = @'
Describe "Get-DiskFreePercent" {
It "returns a number between 0 and 100" {
$r = 42.5
$r | Should -BeGreaterThan 0
$r | Should -BeLessOrEqual 100
}
}
'@
Write-Output $test- Stage 1$test
Positional values or no named parameters
What happens
This prints a small Pester 5 test using a here-string, so you can read the structure without needing Pester installed. Describe names the thing under test, It states the expected behaviour in a sentence, and two Should assertions bound the value. Naming It as a readable sentence is what makes a failure report useful.
Worth remembering
- Describe groups, It is one test, Should asserts.
- Pester 3 and Pester 5 syntax are not compatible. Check the version.
- In Pester 5, setup belongs in BeforeAll or BeforeEach.
- Mock replaces a command so tests do not touch real systems.
Primary documentation
Try it
Illustrative output · values vary by environment
Example reader
Inspect this page's example
Run supported commands against the practice data, or inspect the example without executing it.
Ready to inspect.
Prints a minimal Pester 5 test so you can see the structure.
Show reference output
Illustrative output · values vary by environment
Describe "Get-DiskFreePercent" {
It "returns a number between 0 and 100" {
$r = 42.5
$r | Should -BeGreaterThan 0
$r | Should -BeLessOrEqual 100
}
}Practise this
Import Pester before testing
Import Pester, then display its module record.
The sandbox is visible now. Sign in with Google only when you run or check a task; commands and temporary files are discarded when you leave.
Run a command to inspect its result.