Export (0) Print
Expand All

Start a Runbook

System Center

Updated: December 20, 2012

Applies To: System Center 2012 - Orchestrator, System Center 2012 R2 Orchestrator, System Center 2012 SP1 - Orchestrator

To start a runbook using the Orchestrator web service, you create a new job for the runbook. If the runbook requires parameters, then you must provide a value for each one.

ImportantImportant
Ensure that you provide a value for each parameter that you include in the request. If you specify a parameter in the request but don’t provide a value for it, you may receive a 500 error from the server.

Starting a Runbook with C#

The following example shows how to start a runbook using C#. To start a runbook that has parameters, you must build an XML element containing the GUID of each parameter and a value to populate it with. The runbook in this example has two parameters called Param1 and Param2. Their values are stored in a hash table before being added to the XML for the request. For a runbook that does not have parameters, you can leave the Parameters property of the Runbook object empty.

This example uses a service reference named SCOService and uses the credentials of the current user context. You can uncomment the line that specifies alternate credentials if the current user does not have appropriate permissions to the runbook being started. For more information see Programming in Visual Studio With the Orchestrator Web Service and Authentication and Authorization.

namespace CodeSample.Microsoft.SystemCenter2012.Orchestrator.WebService
{
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Text;
   using System.Net;
   using System.IO;
   using System.Collections;
   using System.Data.Services.Client;
   using SCOService;
   
   public class RunbookOperations 
   {
      public void StartRunbookWithParameters()
      {
         // Details of runbook that we are going to run.
         Guid runbookId = new Guid("00000000-0000-0000-0000-000000000000");
         Hashtable parameterValues = new Hashtable();
         parameterValues.Add("Param1","This is the value for Param1.");
         parameterValues.Add("Param2","This is the value for Param2.");
            
         // Path to Orchestrator web service
         string serviceRoot = "http://server01.contoso.com:81/Orchestrator2012/Orchestrator.svc";

         // Create Orchestrator context
         SCOService.OrchestratorContext context = new SCOService.OrchestratorContext(new Uri(serviceRoot));

         // Set credentials to default or a specific user.
         context.Credentials = System.Net.CredentialCache.DefaultCredentials;
         //context.Credentials = new System.Net.NetworkCredential("user", "pwd", "domain");

         // Retrieve parameters for the runbook
         var runbookParams = context.RunbookParameters.Where(runbookParam => runbookParam.RunbookId == runbookId && runbookParam.Direction == "In");
            
         // Configure the XML for the parameters
         StringBuilder parametersXml = new StringBuilder();
         if (runbookParams != null && runbookParams.Count() > 0)
         {
            parametersXml.Append("<Data>");
            foreach (var param in runbookParams)
            {
               parametersXml.AppendFormat("<Parameter><ID>{0}</ID><Value>{1}</Value></Parameter>", param.Id.ToString("B"), parameterValues[param.Name]);                    
            }
            parametersXml.Append("</Data>");
         }

         try
         {
            // Create new job and assign runbook Id and parameters.
            Job job = new Job();
            job.RunbookId = runbookId;
            job.Parameters = parametersXml.ToString();

            // Add newly created job.
            context.AddToJobs(job);
            context.SaveChanges();

            Console.WriteLine("Successfully started runbook. Job ID: {0}", job.Id.ToString());
         }
         catch (DataServiceQueryException ex)
         {
            throw new ApplicationException("Error starting runbook.", ex);
         }
      }
   }
}
 

Starting a Runbook With Windows PowerShell

Windows PowerShell does not have the ability to use a Service Reference as does a program written using Visual Studio. Instead, you must create an http request that has the required properties and the details of the runbook you want to start. You can parse the response to the request to determine information such as its completion status and the details of the resulting job.

If the runbook requires parameters, you must specify the GUID for each parameter and the value to populate it with. This information is included in a Parameters XML element that uses a CDATA to distinguish it from the XML of the request itself. You can retrieve the parameters for a runbook with and their details with a request similar to the following:

http://server01.contoso.com:81/Orchestrator2012/Orchestrator.svc/Runbooks(guid'00000000-0000-0000-00000000000000000')/Parameters

The following example shows how to start a runbook using Windows PowerShell. The runbook in this example has two parameters. The values for these two parameters are stored in an array variable before being added to the XML for the request. For a runbook that does not have parameters, you can leave the Parameters element of the request empty.

# Details of the runbook we are going to run
$rbid = "00000000-0000-0000-00000000000000001"  
$rbParameters = @{"00000000-0000-0000-00000000000000002" = "This is the value for Param1.";" 00000000-0000-0000-00000000000000003" = " This is the value for Param2."}

# Create the request object
$request = [System.Net.HttpWebRequest]::Create("http:// server01.contoso.com:81/Orchestrator2012/Orchestrator.svc/Jobs")

# Set the credentials to default or prompt for credentials
$request.UseDefaultCredentials = $true
# $request.Credentials = Get-Credential

# Build the request header
$request.Method = "POST"
$request.UserAgent = "Microsoft ADO.NET Data Services"
$request.Accept = "application/atom+xml,application/xml"
$request.ContentType = "application/atom+xml"
$request.KeepAlive = $true
$request.Headers.Add("Accept-Encoding","identity")
$request.Headers.Add("Accept-Language","en-US")
$request.Headers.Add("DataServiceVersion","1.0;NetFx")
$request.Headers.Add("MaxDataServiceVersion","2.0;NetFx")
$request.Headers.Add("Pragma","no-cache")

# If runbook servers are specified, format the string
$rbServerString = ""
if (-not [string]::IsNullOrEmpty($RunbookServers)) {
   $rbServerString = -join ("<d:RunbookServers>",$RunbookServers,"</d:RunbookServers>")
}

# Format the Runbook parameters, if any
$rbParamString = ""
if ($rbParameters -ne $null) {
   
   # Format the param string from the Parameters hashtable
   $rbParamString = "<d:Parameters><![CDATA[<Data>"
   foreach ($p in $rbParameters.GetEnumerator())
   {
      #$rbParamString = -join ($rbParamString,"&lt;Parameter&gt;&lt;ID&gt;{",$p.key,"}&lt;/ID&gt;&lt;Value&gt;",$p.value,"&lt;/Value&gt;&lt;/Parameter&gt;")         
      $rbParamString = -join ($rbParamString,"<Parameter><ID>{",$p.key,"}</ID><Value>",$p.value,"</Value></Parameter>")
   }
   $rbParamString += "</Data>]]></d:Parameters>"
}

# Build the request body
$requestBody = @"
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<entry xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
    <content type="application/xml">
        <m:properties>
            <d:RunbookId m:type="Edm.Guid">$rbid</d:RunbookId>
            $rbserverstring
            $rbparamstring
        </m:properties>
    </content>
</entry>
"@

# Create a request stream from the request
$requestStream = new-object System.IO.StreamWriter $Request.GetRequestStream()
    
# Sends the request to the service
$requestStream.Write($RequestBody)
$requestStream.Flush()
$requestStream.Close()

# Get the response from the request
[System.Net.HttpWebResponse] $response = [System.Net.HttpWebResponse] $Request.GetResponse()

# Write the HttpWebResponse to String
$responseStream = $Response.GetResponseStream()
$readStream = new-object System.IO.StreamReader $responseStream
$responseString = $readStream.ReadToEnd()

# Close the streams
$readStream.Close()
$responseStream.Close()

# Get the ID of the resulting job
if ($response.StatusCode -eq 'Created')
{
    $xmlDoc = [xml]$responseString
    $jobId = $xmlDoc.entry.content.properties.Id.InnerText
    Write-Host "Successfully started runbook. Job ID: " $jobId
}
else
{
    Write-Host "Could not start runbook. Status: " $response.StatusCode
}

See Also

 
Show:
© 2014 Microsoft