Returning an error condition from an advanced function to a module

This topic contains 2 replies, has 2 voices, and was last updated by  Jim Susalla 11 months, 2 weeks ago.

  • Author
  • #76918

    Jim Susalla

    I'm looking for examples or best practices on how to return an error condition from an advanced function that was called by a powershell module. In certain cases, the module needs to process differently based on if a function it called was successful or not. In the spirit of returning only one object from a function, I've seen a few ways:
    1. Using a global error variable.
    2. Setting the returned object to null.
    3. Creating items in the returning object that contain an error/return code and message.
    Is there a best practice, or most efficient way on how to accomplish this?

  • #76921

    Don Jones

    PowerShell doesn't really work off "error codes." You'd normally just have your function throw an exception, using Write-Error or Throw. The calling script would trap that in a Try/Catch construct. It's just like how you'd handle an error from any other command – and functions are merely a kind of command.

    Global variables are flat-out a bad idea. Returning a null object is kinda fine if that's the intended output, versus an actual error condition, but it's a lot less deterministic.

    Whenever I have a question like this, I just ask WWPD? What Would PowerShell Do? Like, if I was using Get-WmiObject – how would I expect to deal with errors from it? How does it indicate an error?

  • #76924

    Jim Susalla

    Thank you for the quick reply and explanation.

You must be logged in to reply to this topic.