Mock [Console]::WriteLine & Break

This topic contains 4 replies, has 2 voices, and was last updated by  Michael 4 weeks ago.

  • Author
    Posts
  • #102884

    Michael
    Participant

    Hi,

    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!
    -Michael

  • #102917

    Don Jones
    Keymaster

    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.

  • #102934

    Michael
    Participant

    Here is the article: https://docs.microsoft.com/en-us/windows-server/administration/performance-tuning/powershell/script-authoring-considerations#avoid-write-host

    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!

  • #102935

    Don Jones
    Keymaster

    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.

  • #102937

    Michael
    Participant

    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.

    🙂

You must be logged in to reply to this topic.