Mock [Console]::WriteLine & Break


I have a section in my code where if specific criteria isn’t met, it causes a break which ends command execution. This is expected and by design, but now I am writing a Pester test for it and not sure how assert that a break just took place.

In addition, since Write-Host is pretty much against the law, I saw a Microsoft article stating to use [Console]::WriteLine() in place of Write-Host. I am wondering I should change this to something else that writes output for the user to see.

Your thoughts/suggestions are welcomed!

If you’re using the Console class, you might as well just use Write-Host.

But from the scenario you describe, the normal pattern I’d expect would be to throw a terminating exception, using Throw. That will end execution and display whatever error message you specify. This has the advantage of being trappable in the event some other code is calling yours. And, therefore, you can use Pester to ensure an error is or is not thrown base don whatever input you’re feeding it.

Here is the article:

Look at the end of the article. It does state to consider using Write-Output as an alternative which should work out fine in my current scenario.

I understand what you are saying about using throw. Ill consider your suggestion. Thanks!

Yeah, I helped write the original version of that ;). “Orders of magnitude slower” doesn’t really matter when you’re terminating execution anyway. It’s not like it’s going to take ten minutes; it’s a few milliseconds slower. It’s console output itself you want to avoid; it can’t be captured, redirected, or directly tested.

And Write-Host in v5 and later actually logs to the Informational pipeline.

Using Write-Output as an alternative is flat-out wrong. It’s a terrible pattern as it corrupts the main output pipeline. I’ll speak to someone about that bit.

Yeah I read about the Write-host logs to the Informational Pipeline in v5. That is good!

And now that I am implementing the throw statement (which makes better sense to do), I actually have no need to use Write-Host or Write-Output for that matter.