Lately I've been involved with SCOM 2007 R2 custom management pack development. We have been using quite a lot of powershell, primarily using the Microsoft.Windows.PowerShellPropertyBagProbe. Today I noticed however that sometimes if a powershell script fails in a workflow, SCOM silently swallows the output to the error pipeline and continues. No 22406 "The PowerShell script failed with the below exception" events in the Operations Manager event log, nothing.
As we want to know if our powershell scripts fail, it seems prudent that we should implement our own error handling and logging. The following script template provides base logging functionality, logging to the Operations Manager event log via the SCOM COM ScriptAPI. The two provided parameters $logErrors and $logDebug can be set as overridable in the workflow, allowing operator customisation of the level of logging.
param([int]$logErrors, [int]$logDebug)
$Script:scriptname = $MyInvocation.MyCommand.Name;
$Script:api = New-Object -comObject 'MOM.ScriptAPI'
$Script:bag = $api.CreatePropertyBag()
function LogError([string] $msg)
{
if($logErrors)
{
Write-Host $msg;
$Script:api.LogScriptEvent($Script:scriptname, 100, 1, $msg);
}
}
function LogInformation([string] $msg)
{
if($logDebug)
{
Write-Host $msg;
$Script:api.LogScriptEvent($Script:scriptname, 101, 4, $msg);
}
}
#Your Script here
trap [SystemException]
{
LogError($_.Exception.ToString());
continue;
}
$Script:bag
Monitoring the monitoring!
From here it is fairly straight forward to create a rule or monitor workflow that detects the events from the event log and alerts on the health of all powershell scripts running in monitoring workflows.