Author Posts

August 8, 2017 at 1:05 pm

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?

August 8, 2017 at 1:08 pm

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?

August 8, 2017 at 1:10 pm

Thank you for the quick reply and explanation.