Skip to content

Instantly share code, notes, and snippets.

@SQLvariant
Last active April 13, 2023 21:46
Show Gist options
  • Save SQLvariant/683b6b16212c7e665d1bffb7fbed98c4 to your computer and use it in GitHub Desktop.
Save SQLvariant/683b6b16212c7e665d1bffb7fbed98c4 to your computer and use it in GitHub Desktop.
A function to test the Examples inside the Help of a PowerShell command.
function Test-Example {
<#
.SYNOPSIS
A function to test the Examples inside the Help of a PowerShell command.
.DESCRIPTION
A function to test the Examples inside the Help of a PowerShell command to see if they can be successfully executed or not.
.NOTES
Currently, this command only supports testing one example at a time.
.LINK
https://gist.github.com/SQLvariant/683b6b16212c7e665d1bffb7fbed98c4
.EXAMPLE
Test-Example -CommandExample ((Get-Help -Examples Import-Excel).Examples | SELECT -First 1) -FullOutput $true
Tests only the first Help Example from the Import-Excel command. Also includes the full test output as on object.
.EXAMPLE
$CommandExamples = (Get-Help -Examples Import-Excel).Examples
$CommandExamples.example | measure
$CommandExamples.example | % {
Test-Example -CommandExample $_
}
Tests all the Help Examples from the Import-Excel command.
#>
[CmdletBinding()]
param (
$CommandExample,
$FullOutput
)
begin {
$sb = {Describe "Testing $($CommandExample.title -replace '-', '')" {
It "Should verify the example command completed successfully." {
$ExampleHistory.ExecutionStatus | Should -Be 'Completed'
}
It "Should verify the count is not blank/empty." {
$ExampleResults.Count | Should -BeGreaterThan 1
}
}
}
}
process {
Write-Host "Testing $($CommandExample.title)"
$CommandExample.code
try {
$ExampleResults = Invoke-Expression -Command $CommandExample.code -ErrorAction Continue
}
catch {
Write-Error "$($CommandExample.title -replace '-', '') Did not work."
}
$ExampleHistory = Get-History -Count 1
$ExampleHistory | SELECT *
$container = New-PesterContainer -ScriptBlock $sb
Write-Output "Running the Tests and Displaying the results"
$TestResults = Invoke-Pester -Container $container -PassThru
}
end {
if ($FullOutput) {
return $TestResults
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment