Mocking Missing Cmdlet ErrorAction with Pester

Following on from the previous Mocking Missing Cmdlets with Pester post, I also encountered another interesting problem when attempting to mock cmdlets that were not present on the test system. This one is more of an edge-case, hence its own post. Just like last time, the tests worked when I had the Hyper-V cmdlets installed, but failed when running within an Appveyor VM.

It’s probably not uncommon that you will need to ensure that the code under test should throw an error here-and-there. Here is a pseudo-example that tests that Get-VM writes an error when passed with a non-existent VM name:

When this test is run it fails:

The problem here is that the stub function is not an advanced function and the –ErrorAction preference switch is ignored! This is easily resolved by adding the [CmdletBinding()] attribute to the stub function definition:

Running the test now results in the expected output:

This is not a Pester issue and it’s not a Powershell issue either. It’s just the way the normal Powershell functions work. But, just in case someone else runs into it I thought it would be worth quickly documenting!


  1. joey on May 4, 2017 at 18:04

    How did you get around mocking write-error and it not writing to the console in the middle of your test? Nice write, thanks for this (e.g. adding cmdletbinding to stub function)!.

  2. joey on May 4, 2017 at 22:45

    Lain, disregard my last question. I got it, I was doing it wrong :).

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.