SMA: Start Runbook / Get Status Runbook from the Rest API via PowerShell

For one of my customer, I had to write a PowerShell script which should be able to start a SMA Runbook but also to retrieve the status of this runbook. Another requirement is to use the REST API instead of the SMA Cmdlets. I used my favorite search engine and I found a blog post from Laurie Rhodes who already published a PowerShell script that was doing almost everything that I need.
 
The original script is available at the following URL: http://www.laurierhodes.info/?q=node/105

I re-wrote some parts of the script and added some functionalities. My version of Laurie’s script is available below:

   
# Original script from http://www.laurierhodes.info/?q=node/105
# Modified by Christopher Keyaert (christopher.keyaert@inovativ.be)

# Ignore SSL Self-Signed certificate  
   add-type @"
        using System.Net;
        using System.Security.Cryptography.X509Certificates;

            public class IgnoreSelfSignedCertificate : ICertificatePolicy {
            public IgnoreSelfSignedCertificate() {}
            public bool CheckValidationResult(
                ServicePoint sPoint, X509Certificate cert,
                WebRequest wRequest, int certProb) {
                return true;
            }
        }
"@
[System.Net.ServicePointManager]::CertificatePolicy = new-object IgnoreSelfSignedCertificate

#--------------
# Step 0. Define Variables
$SMAServer = "SMA.contoso.be:9090"
$RunbookName = "MyRunbook001"

# Create a Credentials object 
$credentials = New-Object System.Management.Automation.PSCredential ("Domain\User",(ConvertTo-SecureString "Password" -AsPlainText -Force))
#$credentials = Get-Credential

# Enable verbose logging
$VerbosePreference = "Continue"
#$VerbosePreference = "SilentlyContinue"

#--------------
# Step 1. Query the SMA server for the Runbook GUID
Write-Verbose ""
 
$URI =  "https://$SMAServer/00000000-0000-0000-0000-000000000000/Runbooks()?`$filter=RunbookName eq '$RunbookName'"
$Response = Invoke-RestMethod -Uri $URI  -Method Get -Credential $credentials 
$StartGUIDURI = $Response.id
 
#--------------
# Step 2. Start the runbook with Name Value pairs for inputs
# * All REST inputs for SMA are as Name Value pairs submitted as JSON
Write-Verbose ""
 
$URI =  “$($StartGUIDURI)/Start”
$Headers = @{“Accept” = “application/atom+xml,application/xml”}
$Body = @"
{"parameters":[
{"__metadata":{"type":"Orchestrator.ResourceModel.NameValuePair"},"Name":"param1","Value":"AAA"},
{"__metadata":{"type":"Orchestrator.ResourceModel.NameValuePair"},"Name":"param2","Value":"BBB"}
]}
"@
 
$Response = Invoke-RestMethod -Uri $URI -Body $Body -Method Post -Headers $Headers -Credential $credentials -ContentType  “application/json;odata=verbose” 
$JobGUID = $Response.Start.'#text'
Write-verbose "JOB Id = $($JobGUID)"
 
#-----------------------
# Step 3. Retrieve the status of the submitted job
# Keep polling until the job status is complete
Write-Verbose ""
 
$URI =  "https://$SMAServer/00000000-0000-0000-0000-000000000000/Jobs(guid'" + $JobGUID  + "')"
$Response = Invoke-RestMethod -Uri $URI  -Method Get -Credential $credentials 
$JobStatus = $Response.entry.properties.JobStatus 
 
 
$Status = (Invoke-RestMethod -Uri $URI  -Method Get -Credential $credentials ).entry.properties.JobStatus
Write-Verbose ""
while ($Status -ne "Completed") { 
  
   Write-verbose "Status = $($Status)"
   Start-Sleep 5
   $Status = (Invoke-RestMethod -Uri $URI  -Method Get -Credential $credentials ).entry.properties.JobStatus
 
  }
Write-Verbose ""
 
# --------------------------
# Step 4. Retrieve the output streams from the Job
Write-Verbose ""

$URI =   "https://$SMAServer/00000000-0000-0000-0000-000000000000/JobStreams/GetStreamItems?jobId='" + $JobGUID +"'&streamType='Any' "
$Result = Invoke-RestMethod -Uri $URI  -Method Get -Credential $credentials 
 
Write-verbose "StreamText = $($Result.content.properties.StreamText.InnerText)"

<#
#--------------
# Step Optional. Retreive all the Runbook Names and IDs
Write-Verbose ""
 
$URI =  "https://$SMAServer/00000000-0000-0000-0000-000000000000/Runbooks()"
$Response = Invoke-RestMethod -Uri $URI  -Method Get -Credential $credentials 

foreach($Rep in $Response)
    {
    Write-Verbose $Rep.content.properties.RunbookID.'#text'
    Write-Verbose $Rep.content.properties.RunbookName
    Write-Verbose ""
    }
#> 

 

I hope this help
Christopher

Tweet about this on TwitterShare on FacebookShare on LinkedInShare on Google+Email this to someoneShare on TumblrPin on PinterestDigg thisShare on RedditFlattr the authorBuffer this pageShare on StumbleUpon

About Christopher Keyaert

Christopher Keyaert is a Consultant, focused on helping partners to leverage the System Center and Microsoft Azure cloud platform. He is also a Microsoft Most Valuable Professional (MVP) for Cloud and Data Center Management and a Microsoft Certified Trainer (MCT).
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *