Thursday, June 29, 2017

How to run a SCOM task from Orchestrator

First we must ensure that the powershell is executed in native mode (normally 64bit) instead of the Orchestrator's internal mode.

I use this type of code:

# -- Set script's parameters, if any

$parms= @("aaaa","bbbb")

# -- Calling powershell, in native mode

$p = Powershell {

  # ... Your code... check $args for parameters

  # -- Return a result object, for instance:

  $ret = @{returnCode=0; returnMsg="OK"; aaa=$args[0]; bbb=$args[1]}
  return $ret

} -args $parms

# -- If need: Set local variables from returned object

$a=$p.aaa
$b=$p.bbb
$rcode=$p.ReturnCode
$rmsg=$p.ReturnMsg

echo "returnCode=$rcode; returnMsg=$rmsg; aaaa=$a; bbbb=$b"


Then we can run the SCOM task in the following way:

$p = Powershell {
# ...........................................................................

# -- Logging: Activate for debugging purposes.

$PROGNAME="runtask"
$MSG_LOGFILE="C:\TEMP\$PROGNAME.log"
#$MSG_LOGFILE=$false
$MSG_SHOW=$false

# ...........................................................................

Function Msg
{
  $dt = Get-Date –f "yyyy-MM-dd HH:mm:ss"
  $msg="$dt | $args"
  if ($MSG_LOGFILE) {
    $sw = new-object system.IO.StreamWriter($MSG_LOGFILE,1)
    $sw.writeline($msg)  
    $sw.close()
  }
  if ($MSG_SHOW) { write-host $msg }
}
# ...........................................................................

# -- SCOM Parameters

# -- MS where to connect
$SCOM_MS="<Insert MS>"
 
# -- Instance: Normally the server's name where to run the task
$SCOM_INSTANCE="<Insert server name>"

# -- Task to execute
$SCOM_TASK="<Insert task name>"

# -- Task's parameters / overrides
$SCOM_TASKPARMS=@{ <... Insert parameters, if any ... > }

Msg "Starting SCOM TASK * Instance:$SCOM_INSTANCE * Task:$SCOM_TASK"

# -- Initialize

Import-module operationsmanager
New-SCOMManagementGroupConnection –ComputerName $SCOM_MS

$Instances = Get-scomclass -name Agent.Management.Class | Get-SCOMClassInstance | ?  {$_.Displayname -eq $SCOM_INSTANCE}
$Task = Get-SCOMTask -name $SCOM_TASK

# -- Execute task

$exec = Start-SCOMTask -Task $Task -Instance $Instances -Override $SCOM_TASKPARMS
$startDate = Get-Date

Msg "Task Started * Exec ID:$($exec.ID)"

# -- Wait for completion

do {
    start-sleep -s 6
 $r=Get-SCOMTaskResult -Id $exec.ID
 Msg "Task $($exec.ID) * Waiting for completion * Current status:$($r.status)"

} while ($r.status -ne "Succeeded" -and $startDate.AddMinutes(2) -gt (Get-Date))

# -- Return

Msg "Task $($exec.ID) * Result:$($r.status) * Output:$($r.Output)"

$ret = @{returnCode=0; returnMsg=$r.Output}

if($r.status -ne "Succeeded") { $ret.returnCode=1 }

return $ret
# ...........................................................................

}