logo

NJP

Mini-Lab: Dynamically Passing Service Catalog Items via JSON to PowerShell

Import · Aug 05, 2018 · article

NOTE: MY POSTINGS REFLECT MY OWN VIEWS AND DO NOT NECESSARILY REPRESENT THE VIEWS OF MY EMPLOYER, ACCENTURE.

DIFFICULTY LEVEL: ADVANCED

VERSION DEVELOPED IN: KINGSTON+

Assumes good knowledge and/or familiarity of Orchestration, Workflows, and Scripting in ServiceNow.

____________________________________________________________________________

In my previous article (Mini-Lab: Passing JSON Through a Custom Activity to PowerShell and Back) I pull together several techniques to show what is possible using JSON in an Orchestration Workflow. The big thing I wanted to bring across is that you can create workflows that do not care about what variables are passed around. In other words you have the ability to "thin" out the need for script maintenance in your workflow by pushing the code to a Script Include library, and much more easily maintain it there.

With this article I present a practical use-case for this methodology.

What I will cover:

1. Using a Service Catalog Item to pass current.variables into a workflow, and converting that object into a JSON string.

2. Utilizing the Custom Activity and PowerShell script from my last article to pass that JSON string to a PowerShell script.

3. In the PowerShell script: Un-boxing JSON, boxing up JSON and returning the JSON to the workflow.

4. Parsing and making use of the JSON results from the Custom Activity.

5. Adding a variable to the Service Catalog Item and showing that the workflow does not care that you do this!

6. Best practices of course.

I highly recommend reading the following articles as they will give context to what I present here, and I will be using scripts and techniques from these as well.

Mini-Lab: Orchestration: Grabbing the Workflow Context Logs

Mini-Lab: Workflow Script Includes

Mini-Lab: Creating a Custom PowerShell Command Activity

Mini-Lab: Creating a Custom PowerShell Script Activity - we will be using the Script Include Libraries from here

PRE-REQUISITES

This lab will work fine on your Personal Developer Instance. If you do not have a personal developer instance goto this link to find out how you can obtain one: link

You will need to install your own local MID Server if you do not have one already.

Install a MID Server on Windows

TIPSWe will build this example Globally scoped. If you want to put this into the actual baseline PowerShell folder then you will need to change the application scope to PowerShell, create the new Custom Activity, and clear out the Category. The new activity will then appear in the PowerShell folder, and you can still use it in your Globally scoped workflows.You might want to create an update set to capture your work. You can click on the Publish button on the new Custom Activity and the Test Workflow to save your work in the update set.

WORK THROUGH THE PREVIOUS ARTICLE

We will be starting where the last article left off. So work through this article before continuing:

Mini-Lab: Passing JSON Through a Custom Activity to PowerShell and Back

DESIGN

This shows the direction we want to take in the creation of our workflow. BTW, DO THIS kind of thing. It is a best practice of development!

image

WORKFLOW MODIFICATIONS

1. In your workflow editor bring up the CCS-Generic PowerShell Run Script Test workflow.

2. Click on the "i" button and navigate to the General tab.

3. Change the Table to: Requested Item [sc_req_item] and click on the Update button.

4. Open the Initialize Run Script activity and modify the Script to the following:

var location = context.name + '.' + activity.name;

// load the scratchpad object with the inbound parameters
new CCS_WorkflowUtils(location).loadServiceCatalogParameters(current, workflow.scratchpad);
gs.info('---> [{1}] Parameters were: {0}', [workflow.scratchpad.parameters, location]);

workflow.scratchpad.host = '127.0.0.1';
workflow.scratchpad.script = 'echobackJSON.ps1';

5. Click on the Update button.

6. Open the Handle Success activity and modify the Script to the following:

var location = context.name + '.' + activity.name;
var echoBack = data.get(4);

if (JSUtil.notNil(echoBack.output) && echoBack.output.indexOf('{') > -1 ) {
    var message = '---> [{0}] Results: \n';
    var outputJSON = JSON.parse(echoBack.output);
        // loop through all the returned variables and print them in the System Log
    for (var item in outputJSON) {
        message += item + ': ' + outputJSON[item];
    }
    // verify that everything came back as expected
    gs.info(message, [location]);
}

Instead of directly addressing the object variables we will instead be generically looping through them without a care as to how many there are! image

7. Click on the Update button.

SCRIPT INCLUDE LIBRARY MODIFICATIONS

1. Navigate to

2. Edit the Script Include CCS_WorkflowUtils.

3. Add the following new function to the Script:

    // generic function to convert the current.variables a parameters 
    // object and place it into the workflow scratchpad object.
    loadServiceCatalogParameters : function(current, scratchpad) {
        var message = 'current.variables parameters: \n';
        var variables = current.variables;
        var parameters = {};
        for (var item in variables) {
            message += item + ': ' + variables[item] + '\n';
            var name = item.replace('v_','');
            parameters[name] = variables[item] + '';
        }
        scratchpad.parameters = JSON.stringify(parameters);
        gs.info('---> [{1}] {0}', [message, this.location]);
    },

Here we will be packing up our current.variables into a JSON object and then turning that object into a string to be passed to our generic Custom Activity. That activity will then pass the string to the PowerShell script where it will be parsed and utilized.

4. Click on the Update button to save your Script.

SERVICE CATALOG ITEM

1. Navigate to Service Catalog > Catalog Definitions > Maintain Items

2. Click on the New button to create a new Request Item.

3. Fill out the form with the following:

Name: Scratchpad Variable Sender

Active: checked

Availability: Desktop Only

Catalogs: Technical Catalog

Category: (anything you want to place it under. I created a new one called Workflow Administration)

Workflow: CCS - Generic PowerShell Run Script Test

Use Cart Layout: Unchecked

Omit Price in Cart: Checked

No quantity: Checked

No proceed checkout: Checked

No cart: Checked

Delivery Time: all zeros.

Short description: Send sample variables to a workflow

4. Right-click on the form header to bring up the context menu and click on Save to save your work.

image

5. Scroll to the bottom of the form to the related lists.

6. From the Variables tab click on the New button.

7. Add three new variables:

Type: Single Line Text

Question: Test 1

Name: v_test_1

Order: 100

Type: Single Line Text

Question: Test 2

Name: v_test_2

Order: 200

Type: Single Line Text

Question: Test 3

Name: v_test_3

Order: 300

Note: The use of v_ in the naming of Service Catalog Item Variables is considered a best practice for easy identification of such variables.

image

7. Click on the Try It button. This will bring up the new Service Catalog Request form.

8. Fill out the form with any day (these are all free-form fields), and click the Order Now button.

image

9. After the Order info form appears navigate to System Logs > System Log > All.

10. Filter for messages starting with "--->", and order by Message descending. You should see entries like the following:

image

I think it is interesting that even though it all comes into the workflow in order that the results are out of order.

Okay, so now let do the cool stuff!

ADDING A NEW SERVICE CATALOG VARIABLE

So in order to show how flexible this model is let's add a new service catalog item variable. We will need to add it to the variable list for the Service Catalog Item, and then modify our PowerShell script to work with the new variable. That is it! Everything else just passes the work from the Service Catalog Item to the PowerShell script.

1. From your instance navigate to Service Catalog > Catalog Definitions > Maintain Items

2. Edit it the Scratchpad Variable Sender item.

3. Scroll to the bottom of the form and add a new variable:

Type: Single Line Text

Question: Test 57

Name: v_test_57

Order: 400

image

MODIFYING THE POWERSHELL SCRIPT

Now we need to add the handling for that new variable in our PowerShell script.

1. From your instance navigate to MID Server > Script Files.

2. Search for and edit up echobackJSON.ps1 script and modify it to look like the following:

#Write-Host $parameterJSON
# parse the JSON parameter string
$jsonObj = $parameterJSON | ConvertFrom-Json

#Write-Host $jsonObj.test_1
#Write-Host $jsonObj.test_2
#Write-Host $jsonObj.test_3
#Write-Host $jsonObj.test_57

# box up the JSON object and echo it back to the ECC Queue for processing
$output = @{}
$output.test_1= $jsonObj.test_1 + " --> completed!"
$output.test_2 = $jsonObj.test_2 + " --> completed!"
$output.test_3 = $jsonObj.test_3 + " --> completed!"
$output.test_57 = $jsonObj.test_57 + " --> completed!"
$objectJSON = New-Object -TypeName PSObject -Prop $output | ConvertTo-Json

WRITE-HOST $objectJSON

All we are doing here is adding our new variable to be handled by the script.

TESTING

1. From your instance navigate to Service Catalog > Catalog Definitions > Maintain Items

2. Edit it the Scratchpad Variable Sender item.

3. Click on the Try It button. This will bring up the new Service Catalog Request form.

4. Fill out the form with any data (these are all free-form fields), and click the Order Now button.

image

5. After the Order info form appears navigate to System Logs > System Log > All.

6. Filter for messages starting with "--->", and order by Message descending. You should see entries like the following:

image

And that's it! The beauty of this model is that it required NO modifications to the workflow or Custom Activity to add a new field to the form! Cool, huh?!?! image

Enjoy!

Steven Bell.

If you find this article helps you, don't forget to log in and "bookmark" and "like" it!

Also, if you are not already, I would like to encourage you to become a member of the ITOM community!

image

image

View original source

https://www.servicenow.com/community/now-platform-articles/mini-lab-dynamically-passing-service-catalog-items-via-json-to/ta-p/2297498