THE SQL Server Blog Spot on the Web

Welcome to - The SQL Server blog spot on the web Sign in | |
in Search

Jamie Thomson

This is the blog of Jamie Thomson, a data mangler in London working for Dunnhumby

Test for a warning message using Pester

Here’s a little ditty that’s worth throwing out (if nothing else so that I can find it later), if you’re not using Pester to test your PowerShell code then this post probably isn’t for you. If you’re not using PowerShell stop reading now.

I wanted to write a Pester test that tested whether or not a piece of code threw a warning or not. I discovered from Understanding Streams, Redirection, and Write-Host in PowerShell that it is possible to redirect stuff in the PowerShell Warning (or Verbose or Debug) stream to the output stream. Here’s an example of doing just that:

"Here is a message that I will send to the warning stream then redirect back to the output stream" | Write-Warning 3>&1 | %{$_.message}


The “3>&1” part says “take the contents of stream #3 (i.e. the Warning stream) and send it to stream #1 (i.e. the Output stream)”. Once its in the output stream you can operate upon it as normal.

In my Pester test I wanted to know whether or not a particular piece of code returned a warning matching a given string. Using the above technique its simply:

(Some-Code-That-Is-Getting-tested) 3>&1) -match "Desired warning message" | Should Be $true

Cool stuff! I love Pester.


Published Thursday, March 5, 2015 11:04 AM by jamiet
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS



Chrissy LeMaire said:

Hey Jamie! Your page was the first one I found when searching for this solution.

Ultimately, I went with WarningVariable instead and wanted to let you know!

Context "Ensuring warning is thrown if database already exists" {

$results = Restore-DbaDatabase -SqlServer localhost -Path C:\github\appveyor-lab\singlerestore\singlerestore.bak -WarningVariable warning

 It "Should warn" {

  $warning | Should Match "exists and will not be overwritten"


 It "Should not return object" {

  $results | Should Be $null



May 18, 2017 10:38 AM

Leave a Comment


This Blog


Privacy Statement