How to use PowerShell to start an Orchestrator Workflow

Okay now I have provided Python and perl articles to start a vRealize Orchestrator (vRO / vCO) workflow via it's REST API so now it's time for a PowerShell script. For this article, I followed the same format as the previous two BUT provided the option to call the script with command line parameters! You may download the script in this article from my vroClientScripts Repository on GitHub.

 The Script

The following code should be saved as something like runWorkflow.ps1:

Param(
    [string]$usr = 'myvROUser',
    [string]$pwd = 'myPassword',
    [string]$vroServer = 'vRO-Server.domain.lab:8281', # in format FQDN:PORT
    [string]$wfid = '2a2c773d-4f34-422e-b427-eddce95669d1',
    [string]$apiFormat = 'json', # either xml or json
    [string]$inputFile = 'e:body.json'# path to input file (either json or xml)
)
#### Make no changes below this line ###############################
# Usage:
# If you run the script with no parameters specified, the default values defined above will be used.
# to run with params, See following example: (Should be all one line)
# NOTE: It is not required to specify name of each parameter, but order will need to match the order in the above params section
# PS E:\> .\runWorkflow.ps1 -usr vcoadmin -pwd vcoadmin -vroServer vro-server.domain.lab:8281 -wfid 2a2c773d-4f34-422e-b427-eddce95669d1 -apiFormat json -jsonFile e:body.json
#
####################################################################

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@

[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

function ConvertTo-Base64($string) {
   $bytes  = [System.Text.Encoding]::UTF8.GetBytes($string);
   $encoded = [System.Convert]::ToBase64String($bytes); 

   return $encoded;
}

$token = ConvertTo-Base64("$($usr):$($pwd)")
$auth = "Basic $($token)"

$headers = @{"Authorization"=$auth;"Content-Type"="application/$($apiFormat)";"Accept"="application/$($apiFormat)"}
$body = Get-Content $inputFile -Raw
# write-output "Using body: " + $body
$URL = "https://$($vroServer)/vco/api/workflows/$($wfid)/executions"
Write-Output $URL
$ret = Invoke-WebRequest -Method Post -uri $URL -Headers $headers -body $body
$headers = $ret.Headers
ForEach ($header in $headers){
    Write-Output $header
}

Note: Before attempting to run the script, be sure to modify the parameters at the beginning of the script to reflect YOUR workflow.

I have kept the script as simple as I can, including the option to NOT Verify the SSL Certificate so that self-signed certs do not prevent the script from running.

The json file

While testing this, my example workflow was the "Create a Record" workflow as noted earlier. That workflow had a number of inputs so these were loaded into a json file. In order to learn more about how to get the correct input json for your workflow, please reference my article: How to use the REST API to Start a Workflow. Please note that the input file could just as easily be an XML file, you would just need to change the input parameter apiFormat to have a value of xml instead of json. That parameter simply tells the script which format to use for the Accept and Content-Type headers.

Here's my example json file:

{
    "parameters": [
        {
            "type": "string",
            "scope": "local",
            "name": "ServerName",
            "value": {
                "string": {
                    "value": "vcac-iaas-01c"
                }
            }
        },
        {
            "type": "string",
            "scope": "local",
            "name": "ServerIP",
            "value": {
                "string": {
                    "value": "192.168.110.89"
                }
            }
        },
        {
            "type": "string",
            "scope": "local",
            "name": "ServerDNS",
            "value": {
                "string": {
                    "value": "corp.local"
                }
            }
        },
        {
            "type": "string",
            "scope": "local",
            "name": "ServerID",
            "value": {
                "string": {
                    "value": "vcac-iaas-01d.corp.local"
                }
            }
        },
        {
            "type": "string",
            "scope": "local",
            "name": "ServerOwner",
            "value": {
                "string": {
                    "value": "administrator"
                }
            }
        }
    ]
}

Example Run

example_run.png

I ran the following from my Windows desktop PowerShell prompt:

PS E:\> .\runWorkflow.ps1 -usr vcoadmin -pwd vcoadmin -vroServer vco-server.domain.lab:8281 -wfid 2a2c773d-4f34-422e-b427-eddce95669d1 -apiFormat json -jsonFile e:body.json
Key                 Value
---                 -----
Content-Length      0
Date                Fri, 30 Jan 2015 18:04:06 GMT
Location            https://vco.domain.lab:8281/vco/api/workflows/2a2c773d-4f34-422e-b427-eddce95669d1/executions/ff8080814b27270a014b3c03a3950419
Server              Apache-Coyote/1.1

When I check the Orchestrator client, I can see that the workflow has run and completed successfully (See screenshot above!)

Help Me Make This Sample Better!

As noted at the beginning of this article, I don't know Python but I managed to get a very simple example script working here. Please submit your comments and/or improvement suggestions to help increase the value and usefulness of this simple script.

Thanks!

Comments  

0 #4 Nick 2016-11-16 10:16
Thanks for this great article.
Can you please tell me which method is better to invoke workflow java REST SDK or powershell script?
+1 #3 Desmond 2016-03-17 05:53
Apologies, need a little help here. Got this error while running. :cry:

Invoke-WebReque st : The 'Content-Type' header must be modified using the appropriate property or method.
Parameter name: name
At C:\Users\Admini strator\serveru p.ps1:45 char:8
+ $ret = Invoke-WebReque st -Method Post -uri $URL -Headers $headers -body $body
+ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Invoke-WebReque st], ArgumentExcepti on
+ FullyQualifiedE rrorId : System.ArgumentExcepti on,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
0 #2 Chris Dadswell 2015-09-23 12:29
Thanks for a great article!

For info, in my script I reduced the convert to base64 down to a one liner;

$auth = $username + ':' + $upassword
$encodedPassword = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($auth))
$objHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$objHeaders.Add("Authorization", "Basic $($encodedPassword)")
$objHeaders.Add("Content-Type","application/json")
$objHeaders.Add("Accept","application/json")
0 #1 fab 2015-07-27 12:48
hello

excellent script 8) , but don't be able to use it with another WF.

Can you explan how to do to execute a WF that need :
- a host (vCAC:VCACHost)
- a propertyName ("application")
- an item ("TE - Test")

Thanks for your help

Search

Book Shelf

 
Experts Exchange

NUC Lab Kit

Below are my thoughts for a vSAN nuc lab. Since I already have cables, not including them here. I ordered (and received by Nov 30, 2016)
3 x nuc, 3 x 32GB Crucial mem, 3 x Toshiba NVMe drive, 3 x Startech USB to GB NIC, and 3 x Crucial 1TB SSD. I've also been very happy with my Cisco SG300-10 so I bought one more since my existing one only has one port available. Each of the items listed here are linked below - all were purchased using the provided links below.
single NIC (See this post for details on using the USB -> GB NIC item listed below

I stayed with the i5 for the power consumption and form factor vs. the i7 Skull Canyon ;)