Ben Sweetser

6 minute read

We are experimenting with new training content delivery methods. This tutorial blog post is one of those experiments. We are very interested in your feedback. Please let us know what you think about this format and the content in the comments below.

Introduction

Years ago, when I first started working with the ServiceNow platform, I learned about Scripts - Background. Scripts - Background was this magical place in the platform where you could run any server-side script. It became my testing ground for any server-side method I wanted to learn about or new script I wanted to test because I did not need to configure When to run logic around it like a Business Rule. Running a script in Scripts - Background was as easy as putting a script in the field and clicking the Run script button.

I will admit that for most scripts I need to run on an instance these days, I prefer other ways to execute my scripts over Scripts - Background. Syntax highlighting and checking are just too helpful for me to pass up if I have access to them. The value of Scripts - Background lies in its simplicity. No need to create a record. Just write or paste in a script and run it.

NOTE: Scripts - Background should be used very carefully and only in non-production environments. Free-form JavaScript can negatively impact data and system performance.

In this post, you learn how to work with Scripts - Background to add some demo data. You also learn how to work with the rollback capability to remove the demo data.

Running Scripts - Background

To open Scripts - Background, use the Application Navigator to open System Definition > Scripts - Background.

The Scripts - Background UI has a field for the script and options to set scope, rollback, and cancel long running scripts.

  • Run Script: Button to run the script.
  • Scope selector: Choice list of application scopes. Default to the current scope of the main ServiceNow window.
  • Record for rollback?: Captures database updates and insertions to rollback when possible.
  • Execute in sandbox?: Runs the script with restricted rights. Refer to the documentation on The script sandbox property for details on what methods are restricted. Executing in sandbox can prevent potentially harmful methods from running, but could prevent the script from its intended purpose. This example shows the messages logged when insert methods are run in sandbox.

    A script that tries to insert records when run in sandbox returns Security restricted messages.

  • Cancel after 4 hours: Cancel long running scripts after 4 hours. Keep this selected unless you are sure your script needs more time. Even then, you should consider breaking up the work into smaller chunks.

After the script executes, examine the results.

The Scripts - Background output has three sections: script results, rollback and database updates, and script output. Each section is separated by a horizontal rule.

  • Script results: The time the script took to run and the scope in which the script ran.
  • Rollback and database updates: Access to rollback (if selected) and database updates made by the script.
  • Script output: Logging generated by the script. Add messages with gs.log (global) or gs.info (scoped app) statements.

DEVELOPER TIP: If the script does not execute as expected and you need to adjust the script and run it again, click the browser’s back button to return to the Scripts - Background window with the script you ran.

Add Sample Users

In this section of the tutorial, you run a script in Scripts - Background to create some sample user records.

  1. Use the Application Navigator to open System Definition > Scripts - Background.
  2. Set the in scope choice list to global.
  3. Copy this script and paste it into the Run Script (JavaScript executed on server) field.

    
            // Set the number of users to create  
            var numUsers = 3;
    
            // Define a loop to create users  
            while(numUsers > 0){
                    
                // Create a User record with numUsers as an index
                var grUser = new GlideRecord('sys_user');
                grUser.user_name = "mabel" + numUsers;
                grUser.first_name = "Mabel";
                grUser.last_name = "Gerkowski " + numUsers;
                grUser.insert();
    
                // Log user creation - use gs.info in scoped applications
                gs.log("User created: " + grUser.user_name);
    
                // Decrease numUsers by 1
                numUsers--;
            }
    
    
  4. Click the Run script button.

  5. View the results of the script.

    1. How many records were added?
    2. How long did the script take to run?
    3. What information was logged?
  6. Verify user creation.

    1. Use the Application Navigator to open User Administration > Users.
    2. Find users with a User ID that contains mabel. You should have three Mabel Gerkowskis.

Rollback

If the Record for rollback? option is selected, the database actions performed by the script can be rolled back.

Access the Script Execution History from the Scripts - Background results by clicking available here in the Script execution history and recovery available here message.

To open the history after navigating away from the results, use the Application Navigator to open Rollback & Recovery > Script Execution History. Open the script execution to rollback and click the Rollback Script Execution… Related Link. Confirm the rollback.

NOTE: Script Execution History is only stored for seven days. After that, the execution history is no longer available to view or roll back.

  1. Roll back user creation.
    1. Use the Application Navigator to open Rollback & Recovery > Script Execution History.
    2. Click the timestamp in the Started column for the script execution to rollback.
    3. Click the Rollback Script Execution… Related Link.
    4. In the Rollback entire operation? dialog, type yes to confirm the rollback and click the OK button.
  2. Verify the rollback.
    1. Use the Application Navigator to open User Administration > Users.
    2. Find users with a User ID that contains mabel. You should not have any *Mabel Gerkowski*s.

Did you do the hands-on exercise in this blog? Click here to let us know!

Challenge - NeedIt

If you have taken training on the Developer Portal, you should have the NeedIt application and table. Use what you have learned about Scripts - Background here to create some new NeedIt records. Log details for the records created. If you do not yet have NeedIt, use the instructions in Exercise: Prepare Instance for Client-side Scripting to configure your instance with the NeedIt application.

Considerations

  • What fields do you need to supply values for?
  • How do you log details for the records created?
  • How do you run the script in the NeedIt scope?

Tips and Closing Thoughts

Scripts - Background is a simple, but powerful tool to run JavaScript in a ServiceNow instance. While Scripts - Background can be used for quick scripting logic tests or for quick commands in a test environment, I recommend using an On Demand Scheduled Script Executions (SSE). Scheduled Script Executions have these benefits:

  • The Script field includes syntax coloring and code syntax checking.
  • SSEs can be captured in an application.
  • The script can be edited without relying on the browser’s back button or saving in another file.
  • SSEs can be executed on demand.

On the downside: rollback is not available for these script types. Regardless of how you execute a script on the ServiceNow platform, proceed with caution.

Challenge Answer

Here is a possible answer for the Challenge. It needs to be run in scope x_58872_needit.


    // Set the number of NeedIt records to create  
    var numRecords = 5;

    // Define a loop to create NeedIt records  
    while(numRecords > 0){
        
        // Create a NeedIt record with numRecords as an index
        // Fields may vary depending on which training you have completed
        var newNI = new GlideRecord('x_58872_needit_needit');
        newNI.u_requested_for = "Fred Luddy";
        newNI.u_requested_for_email = "fred.luddy@example.com";
        newNI.u_when_needed = gs.daysAgo(-numRecords - 2);
        newNI.short_description = "NeedIt generated by Scripts - Background";
        newNI.insert();

        // Log NeedIt record creation
        gs.info("NI created: " + newNI.number + " - " + newNI.short_description);

        // Decrease numRecords by 1
        numRecords--;
    }


Comments