You are currently viewing Wonders Of ServiceNow Background Scripts In 2024

Wonders Of ServiceNow Background Scripts In 2024

How to practice scripting in ServiceNow? This is one of the few questions that is asked by people all the time, and the solution to that is the ServiceNow background script. This utility is a free resource ServiceNow provides and can do amazing wonders if you understand it well.

It will have some adverse effects on your instance if not dealt with properly, we will discuss this later in this post.

What is the background script in ServiceNow?

  • The utility provided by ServiceNow executes free-form javascript code to run any server-side script.
  • Use it for any server-side code
  • It is mainly used to test your piece of code
  • You can use it for debugging your code as well
  • It is easy to run and manage and see the output
  • It is more suitable for non-production environments, avoid it in live production for any data loss or performance degradation.

Components of ServiceNow Background script?

In the above image, there are various components of a background script. Let’s discuss it one by one.

  • Script window -use this to write your script (only server-side code works properly)
  • Run Script – Button to execute the script
  • Scope selector – use it to select the scope where you want to execute your script. such as global or scoped app
  • Record for rollback checkbox – If you want an option to rollback the changes done by script.
  • Execute In Sandbox – It is the safer side execution of background script in restricted security that prohibits any modification of data such as insert, delete and update. However, in this option, the script may not work as expected on the full scale of data.
  • Cancel after 4 hours – One more option to minimize its unnecessary execution. In case you do not want the script to run more than 4 hours use this option. The system will terminate the script after four hours. Ideally, we should avoid running background scripts to have this big execution time.
  • Execute as scriptlet checkbox – It provides more flexibility to your script. All global objects and functionality will be available if this checkbox is true.

Who can access ServiceNow background scripts?

  • By default, it is available to the admin without elevated privilege
  • But in case you want it to be available in elevated privilege update the following property to security_admin
  • glide.script_processor.admin

How to write background script in ServiceNow?

Please use the following steps to execute the script in the background script.

  • Navigate to System Definition -> Script – Background
  • Write your code in the window
  • Click the “Run Script” button to execute
  • The script executes and the output will be displayed in the output window.
  • Below is a ServiceNow background script example

In this script, I am displaying 10 incident records with high priority.

Please copy the below code and try it in the background script:-

var gr = new GlideRecord("incident");
gr.addQuery('priority','1');
gr.setLimit(10);
gr.query();
while(gr.next())
gs.print(gr.number);

What does a background script display?

As a whole a background script displays the following-

  • script output
  • script related other information
  • error messages( if any)

How do you check background script history in ServiceNow?

  • Any script that runs all its execution history gets stored in the Script Execution Histories table.
  • The table’s full name is sys_script_execution_history
  • It has all the basic details such as who executes it, start and finish time, transaction ID, script, result and result metadata.

How to stop the background script in ServiceNow?

If the script is running unexpectedly, it is very important to stop it. otherwise, it will hamper the performance of instances and data loss. Following are the ways to stop it.

  • Kill the background script process from active transactions
    • Go to System Diagnostics -> Active Cluster Transactions
    • Select your process from the list view
    • Open List actions and click Kill
    • You can do this by opening the record of your process and clicking the kill button
    • The process terminates in a few seconds.
  • In case it is still active, you have to call ServiceNow support and ask to stop it.
  • They generally restart the node on which your process is running

How to rollback your modifications made by FiX script or Background Script?

  • Yes, it is possible. So don’t be panic.
  • Go to sys_rollback_context table and you will see many type of records
  • open your script and click on rollback related link

How to call script include from background script in ServiceNow?

  • Calling a script include from a background script is possible
  • It is the same as we call a script include from any other server script such as ACL, or business rule.
  • Use the following syntax
    • new MyScriptInclude().myFunction();
    • In the below example, I am calling a function “callScript()” of a script include named “TESTACL” and printing its return value.

Script Include Code:-

var TESTACL = Class.create();
TESTACL.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    type: 'TESTACL',
    callScript: function() {
       return "Script Include Is Working" ;
    }
});

Backgound Script Code:-

var test = new TESTACL().callScript();
gs.print(test);

How to print in background script ServiceNow?

As provided in the above script, use gs.print() function to print values in a background script.

Script Background & Fix Scripts in ServiceNow?

Fix script is the best approach when you install a new application or want some data fixes to be running after making some changes in prod. The best feature of a fix script is you can monitor its execution and check the progress and you can kill the transaction as well.

Never execute any insert/update/delete script from the script background since if it takes a long time the browser will timeout and also if any error comes in the script it may get into some loop.

How to cancel the background script in ServiceNow?

  • It is possible to limit the execution time of the background script (…/sys.scripts.do)?
  • Yes, you can type https://<your_instance>.service-now.com/cancel_my_transaction.do into the address bar and it will also cancel the transaction currently running.

What are the limitations of the ServiceNow background script?

  • The limitation of the background script is to return 50k records only at a time
  • it can cause performance issues

How to get black and with code look of background script?

You have to install SN Utils – Tools for servicenow” extension in your browser.

Are ACL’s executed when we try to run scripts in Background scripts?

Its not about Background script. GlideRecord Query in general don’t consider ACLs. So you should use GlideRecordSecure instead.

How to trigger an event from background script in ServiceNow?

  • Yes, it is possible to trigger an event from the background script
  • It is the same as you do event calls from other server-side scripts such as business rules etc
  • The only exception here is there is no availability of objects such as current, previous etc in the background script
  • It is used to do testing by triggering an event
  • Use the following syntax
    • gs.eventQueue(‘<Event Name>’,<GlideRecord Object of the record>,<parm 1>, <parm 2>);

ServiceNow Background Script Vs Scheduled Job


Here’s a comparison of ServiceNow Background Script and Scheduled Job in a table format:

FeatureBackground ScriptScheduled Job
Execution LocationExecuted directly within the ServiceNow UIExecuted automatically at predefined intervals
PurposeAd-hoc tasks, troubleshooting, quick script executionAutomating repetitive tasks
AccessibilityAccessible from the ServiceNow UIConfigured in background and managed via Scheduled Jobs list
Execution ControlExecuted on-demandExecuted at specific intervals or times
Use CaseOne-time tasks, testingRegular maintenance tasks, data cleanup, report generation
VisibilityVisible and editable within the UIConfigurable and managed through Scheduled Jobs list

How to print an array in the background script in ServiceNow?

  • Yes, you can print an array in the background script
  • Suppose, the script include is returning an array and in script include it can be easily access
  • you need not to do any other type of conversions etc now, it is all automated

Code of Script Include:-

var TESTACL = Class.create();
TESTACL.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    type: 'TESTACL',
    callScript: function() {
		var arr = ['january','feburary','march','april'];
       return arr;
    }
});

Background Script Code:-

var array = new TESTACL().callScript();
gs.print("Complete array:- "+array);
gs.print("Part of array:- "+array[3]);

What is ServiceNow background script scope?

  • It is the restriction of background script upon application scope

Why ServiceNow background script not authorised message appear?

Yes, you may recieve not authorised message while access in background scripts.

  • When running out of scope
  • When you try to run the script without the security_admin privilege
  • When you try to run it from other roles i.e. non-admin role

Provide serviceNow background script delete records example?

We can delete records of a table using background script. For this we mostly use GlideRecord API.

Following example delete record from incident table with priority is 1.

var rec = new GlideRecord('incident');
rec.addQuery('priority','1');
rec.query();
while (rec.next()) { 
 gs.print('High Priority incident ' + rec.number + ' deleted');
 rec.deleteRecord();
}

How to display ServiceNow background scripts log?

How to check ServiceNow background script execution history?

What is the ServiceNow background script scope?

What is background script role in servicenow?

How to call function in background script servicenow?

Where to write script in ServiceNow?

Leave a Reply