liveBook · Manning

Parameter filter

As explained in Practical Automation with PowerShell: Effective scripting from the console to the cloud

A parameter filter is a mock-selection condition that matches calls according to the parameters supplied to a command.

A parameter filter selects which invocation a mock handles when a command is called multiple times with different parameters. In Pester, the filter inspects values such as `$URI` or `$Command`, allowing one call to use a mock while another follows a separate mock or behavior. section 13.3.3 section 14.1.3

Use parameter filters to keep command-level mocks aligned with the operation being tested:

  • Match a parameter value, such as `$URI`, to restrict a mock to one call site. section 13.3.3
  • Route different invocations to different fixtures, such as saved HTML files for separate search results. section 13.3.3
  • Assert that the expected command and parameter combination invoked its mock the required number of times. section 14.1.3
  • Reuse one test structure for multiple cases by combining filtered mocks with a collection of expected values. section 14.1.3

Filtering a ConvertFrom-Html mock

A function calls `ConvertFrom-Html` once with `-URI` and later with `-Content`. Filter the first mock with `{ $URI }`, load a fixture named from the URI, and mock `Invoke-WebRequest` separately for the later call. Pester ignores the filtered mock when the command uses the other parameter. section 13.3.3

Mock ConvertFrom-Html -ParameterFilter{ $URI } -MockWith {
    $Path = Join-Path $PSScriptRoot "$($URI.AbsoluteUri.Split('=')[-1]).html"
    ConvertFrom-Html -Path $Path
}
 
Mock Invoke-WebRequest -MockWith {
    $Path = Join-Path $PSScriptRoot "$($URI.AbsoluteUri.Split('=')[-1]).html"
    $Content = Get-Content -Path $Path -Raw
    [pscustomobject]@{
        Content = $Content
    }
}

Inspect the complete Pester mock definitions, including URI-based fixture selection and the PowerShell object returned by `Invoke-WebRequest`. section 13.3.3

How Practical Automation with PowerShell: Effective scripting from the console to the cloud covers it

How deep it goes
Defines filters through working Pester mocks and assertions, but stops short of broader mocking internals.
Examples
Uses URI-filtered HTML conversion, URI-derived files, and a `df /boot` mock selected through `$Command`.
What it assumes
Assumes PowerShell commands, parameters, mocks, and basic Pester tests; teaches parameter-based mock routing through examples.
What you can do after
Apply it via Pester to isolate repeated calls, select fixtures, and verify mock invocation counts.
How it connects
Connects Pester mocks, test fixtures, command parameters, and invocation assertions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practical Automation with PowerShell: Effective scripting from the console to the cloud. The section links point to the parts of the book it draws on.