Powershell Workflow Exit Handling

As I mentioned here, I post on things that I find interesting, I don’t care what any of you think  😀

And this one just tickled memories of several things I’ve stumbled across along the way that fit together nicely (I hear an old Reese’s commercial jingle coming on).

I just read a post on the OpsMgr.Authoring newsgroup asking about detecting errors in PowerShell scripts.  PowerShell can be used to deliver discovery and property bag data as mentioned here (I saw another blog out there about it, but I can’t find the link now).  However, if the script logic itself fails or encounters an error, there are multiple layers through which the error code must be fed back to OpsMgr.

Thanks to the broad reach of the blogosphere and search engines, I am happy to be able to present the following mashup!

First, change the command XML in my MyMP sample from

<CommandLine>.\PSDisc.ps1</CommandLine>

to

<CommandLine>-Command " &amp; { .\PSDisc.ps1; exit $LASTEXITCODE }"</CommandLine>

(H/T to alemyis’ comment for that syntax)

Next, add the <ExitCodeMatches> tag to the end of the CommandExecuter module.

       ##SCRIPTCODE….
      </Contents>
    </File>
  </Files>
  <EventPolicy>
    <ExitCodeMatches Operator="MatchesRegularExpression">[^0]+</ExitCodeMatches>
  </EventPolicy>
</Configuration>

(You can also use DoesNotMatchRegularExpression)

Next, use the PowerShell Try-Catch function available here, but instead of using Throw, which will result in a return code of 1, use exit ###.

Better yet, encapsulate it as a common function by using a custom module as the momteam blogged here!

The result will be an event that looks something like this (my script used "exit 22;" for the particular error condition):

 

(12/8/08 Updated with EventPolicy; Thanks to AHood for catching the error)

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s