You are currently viewing Common ServiceNow Background Scripts 2024

Common ServiceNow Background Scripts 2024

Hello Everyone, below is the collection of some common background scripts. These are collected and tested on demo instances. Please see if it suits your requirements.

My Youtube Channels

[youtube-feed feed=1][youtube-feed feed=3][youtube-feed feed=4]

Background script to find users with no location value?

Question: How to write a background script that will give you a list of users whose location is empty?

var userGr = new GlideRecord('sys_user');
userGr.addQuery('location', '');
userGr.query();
var totalCount = 0;
while (userGr.next()) {
    gs.print('User with empty location: ' + userGr.getValue('name'));
    totalCount ++;
}
    gs.print('Total Count of users with empty location: ' + totalCount);

Background script to insert record in one table upon insert of another table?

Scnerio:- I have two tables Table 1 and Table 2, I want to write a script for the insertion of records. Once I insert the record in the Table1, it automatically inserts the record in the table2 record.

var gr = new GlideRecord("u_mytable");
gr.u_name = "abraham.lincoln";
gr.u_mobile_number = "040-00282262";
gr.insert();
var grc = new GlideRecord("u_mytablecopy");
grc.u_name = gr.u_name;
grc.u_mobile_number = gr.u_mobile_number;
grc.insert();

Background script to delete record in one table upon delete of another table?

Scnerio:- I have two tables Table 1 and Table 2, I want to write a script for the deletion of records. Once I delete the record in the Table1, it automatically deletes the record in the table2 record.

var gr = new GlideRecord("u_mytable");
gr.addQuery('u_name',"abraham.lincoln");
if(gr.next()){
var grc = new GlideRecord("u_mytablecopy");
grc.addQuery('u_name',gr.getValue('u_name'));
if(grc.next()){
grc.delete();
}
gr.delete()
}       

Print the last 5 incidents created yesterday.

Scnerio:- I want to write a background script to print the last 5 incidents created yesterday and also we have to implement it only using the background script. 

var gr=new GlideRecord('incident');
gr.addEncodedQuery('sys_created_onONYesterday@javascript:gs.beginningOfYesterday()@javascript:gs.endOfYesterday()');
gr.orderByDesc('sys_created_on');
gr.setLimit(5);
gr.query();
while(gr.next())
{
    gs.print("The Incident Number is "+gr.number);
}

Force logout User(s) from the background script

 Scnerio:- Log out all users who are currently logged into ServiceNow before an outage. Usually we communicate to all the users about the outage days before the actual Outage start date. But just to make sure no one is currently logged into the instance during the outage, we can run the below background script few minutes before the actual outage start time.

var userGr = new GlideRecord('sys_user');
userGr.addEncodedQuery('active=true^locked_out=false^user_name!='+gs.getUserName());
userGr.query();
while(userGr.next()){
  var userName = userGr.getValue('user_name');
  GlideSessions.lockOutSessionsInAllNodes(userName);
}

Output:

locked_out user abel.tutor
locked_out user julio.curry
locked_out user sergio.chang
locked_out user ramon.amaral
locked_out user Howard.Lewis
......
.....
....
...
..
.

Logout a particular user using background script?

Use Case 2: Annoy a friendly co-worker by logging them out

var userName = 'your coworkers user name';
GlideSessions.lockOutSessionsInAllNodes(userName);

Scnerio to choose background script over others?

Scnerio:- If I wanted to make a change to all computer records in my CMDB to show them as Archived in the Operational Status field, would a background script be the most appropriate way to make that global change?

Solution:- You can either write a scheduled script or a background script if this is a one-time activity.

How to write servicenow background script to delete records?

var rec = new GlideRecord('incident');
rec.addQuery('active',false);
rec.query();
while (rec.next()) { 
 gs.print('Inactive incident ' + rec.number + ' deleted');
 rec.deleteRecord();
}

How to Use JSON.stringfy() in the background script?

var jsonObj = {}; // declare empty object here...
var res = {} ; // declare your res here
var parsedData = {} // declare your objects here...
var caseR = new GlideRecord('sn_customerservice_case');
caseR.addEncodedQuery('state=10^number=CS0001031');
caseR.query();
if(caseR.next()){
gs.print(caseR.short_description);
jsonObj = caseR.u_json_output;
gs.print(jsonObj);
res = JSON.stringify(jsonObj);
gs.print(res);
parsedData = JSON.parse(jsonObj);
gs.print(parsedData);
gs.print(parsedData.u_supply_planner_field_1[0].original_value);
}

Background script to retrieve rejected sctasks?

Scnerio:- I need help with the Background script to retrieve SCTASK with work notes containing reject/rejected

var grTask = new GlideRecord('sc_task');
grTask.addEncodedQuery('work_notesLIKEreject');
grTask.query();
while(grTask.next()){
    gs.print(grTask.number);
}

How to start a workflow from the background script?

Scnerio:-I have a workflow that is running on a schedule. I wanted to check if I can run that workflow from background script on ad-hoc without modifying the workflow?

var gr = new GlideRecord('table');
gr.initialize();
gr.insert();
var wflw = new Workflow();
wflw.startFlow(wflw.getWorkflowFromName('give the workflow name'), gr, 'insert');

Background Script to remove character at the end?

Scnerio:- I need to write a background script to remove _) from the end of the serial number in alm_hardware.   Any assistance is appreciated.

//script 1
var al = new GlideRecord("alm_hardware");
al.addEncodedQuery("serial_numberENDSWITH_)");
al.query();
while(al.next()){
gs.print("Before Update:"+al.getValue("serial_number"));
var str = al.getValue("serial_number").toString();
var str1 = str.split('_');
gs.print("After Update:"+str1[0]);
al.setValue('serial_number',str1[0]);
al.setWorkflow(false);
al.autoSysFields(false);
al.update();
}
//Script 2:-
var al = new GlideRecord("alm_hardware");
al.addEncodedQuery("serial_numberENDSWITH_)");
al.query();
while(al.next()){
gs.print("Before Update:"+al.getValue("serial_number"));
var str = al.getValue("serial_number").toString();
var str1 = str.replace(/[^a-zA-Z0-9]/g, '')
gs.print("After Update:"+str1);
al.setValue('serial_number',str1);
al.setWorkflow(false);
al.autoSysFields(false);
al.update();
}

Export data from the array to an Excel sheet in ServiceNow.

Scnerio:- I am currently using a script that stores all duplicate CI serial numbers in an array. Now my requirement is to export the data stored in the array to an Excel file. 

var grX = new GlideRecord("sys_user");//some where we need to save the file here I am attaching on one of the user record logged in one
var csvData="";//This should always be in the 2D array format
//FieldLabel1,FieldLabel2,FieldLabel3,FieldLabel4=====This Row is For Header of CSV
//Val11,Val12,Val13,Val14==== Row 1
//Val21,Val22,Val23,Val24 ==== Row 2
  grX.addQuery('sys_id',gs.getUserID());
  grX.query();
  if(grX.next())
  {
csvHeader="UserID,Name,Company\n";
csvRows1="ABC1,Mario1,SPM1\n";
csvRows2="ABC2,Mario2,SPM2\n";
csvRows3="ABC3,Mario3,SPM3\n";
csvData=csvHeader+csvRows1+csvRows2+csvRows3;
    var grAttachment = new GlideSysAttachment();
    grAttachment.write(grX, "User Details.csv", 'application/csv', csvData);
  }

Use string operations using background script?

Scnerio:- I want to update a field and replicate it for all records through the background script. I have a field ‘Name'” and updated this field with a combination of 2 fields.

Name = Field 1 value + XYZ + Field 2 value

//You will have to update table name, query, filed names etc as per your requirements
var gr = new GlideRecord('table_name');
gr.addEncodedQuery();// add query to udpate existing records from your table
gr.query();
while(gr.next()){
gr.field_3 = gr.field_1 + " XYZ " + gr.field_2;
gr.update();

}

ServiceNow Background script to close the bulk RITMs?

Scnerio:-

I need to close the RITMs with the condition below using the background/fix script.

1.Catalog item specific = ‘xyz’
2. The assignment group is empty
3. State is open/work in progress/pending

I need to write a background script to close the RITMs that contain the above condition, Let me know how to write the script for this

var ritm = new GlideRecord('sc_req_item');
ritm.addQuery('cat_item', '<sys_id of catalog item>');
ritm.addQuery('state', 'IN', '-5,1,2');
ritm.addNullQuery('assignment_group');
ritm.query();
while (ritm.next()) {
	ritm.state = 4;
	ritm.update();
}

Restart workflow from background script?

Scnerio:- I’m trying to restart a workflow running on a custom table to restart from the background script. The workflow restart function call accepts the current object of type GlideRecord but the challenge is how to call the current object in the background script. 

var gr = new GlideRecord("change_request");
gr.addQuery("sys_id", "fbeb1a480fd76b40e1f30dbce1050e42");
gr.query();
if (gr.next()) {
new Workflow().restartWorkflow(gr);
}

Update multiple records using background script

 Scnerio:- I need to update couple of the records with the help of the background script. The field I need to update is a free text field, which = to value NAAM. I need to update it so it says NAM.

var rg = new GlideRecord('incident');
rg.addQuery("u_alias1", "=", "NAAM");
rg.query();
while(rg.next()){
rg.setValue('u_alias1','NAM');
rg.update();
}

Use gs.getUser in background scripts?

Scnerio:-

How can I execute below script in background script for one of the user?
gs.getUser().isMemberOf(‘abc’)?

var username = 'abel.tuter';
var isMember = gs.getUser().getUserByID(username).isMemberOf('abc');
gs.info(isMember);

Delete multiple records using background scripts?

var gr = new GlideRecord('pa_scores');
gr.addQuery('breakdown.name','=', 'Model Category');
gr.addEncodedQuery('sys_created_on<=' + gs.dateGenerate('2016-03-31','23:59:59')); 
gr.query();
while (gr.next()) {
   gr.deleteMultiple();
}

How do you clear the field by background script?

Scnerio:- After saving, I want to empty the values ​​of the “client_id” and “client_secret” fields in the oauth_entry table.

var test = new GlideRecord("oauth_entity");
test.addQuery("sys_id", "f7529bae87c0511006738517cebb3514");
test.query();
if(test.next()){
test.setValue("client_id", "");
test.setValue("client_secret", "");
test.setWorkflow(false); //Do not run business rules
test.autoSysFields(false); //Do not update system field
test.update();
}

Incident Closing background scripts?

Scnerio:-

I have 10 random incident numbers with different states which have to be closed through background script.

var gr = new GlideRecord("incident");
gr.addQuery("number",'IN',"INC00001X,INC0002X"); // pass comma separated values for all those 10 tickets numbers
gr.query();
gs.print(gr.getRowCount());

Write a servicenow background script export to excel?

Write a servicenow background script to impersonate?

Provide a background script to update a field in ServiceNow?

How to use gs.print in background script in ServiceNow?

Write a servicenow background script to update multiple records?

How to execute servicenow background script as scriptlet?

Write a background script to update records in servicenow?

Provide a servicenow script to update record?

Background script to erase the values from Table: cmdb_ci_comm

  Scenario:-

Can anyone please give me the background script that must erase the values in the phone number field where the country is Japan?

var comm = new GlideRecord('cmdb_ci_comm');
comm.addQuery('country', xxxx); // value of 'Japan', could be sysID/string/etc
comm.query();
while(comm.next()){
comm.setValue('phone_number', '');
comm.update();
}

Background Script to update Date Fields?

Scnerio:- I have to update some records in the Change table i.e. I have to set work start with created date, and work end with created +30 seconds.

var gr= new GlideRecord('change_request');
gr.addEncodedQuery('short_descriptionLIKEISPW-change^active=true^sys_created_by=ispw');
gr.setLimit(2);
gr.query();
while(gr.next())
{
gr.work_start = gr.sys_created_on;
gr.requested_by_date = gr.sys_created_on;
var date = new GlideDateTime(gr.sys_created_on);
date.addSeconds(30);
gr.setValue('work_end', date.getValue());
//gs.print(date.getValue());
gr.update();
}

Background script to display short descriptions?

Scenario:-

I have the below background script, which will display a matching Short description.

var arr = [];
var regex = /SAP/i;
var strSD='';
var stdDesc='';
var gr = new GlideRecord('incident');
gr.query();
while (gr.next())
{
strSD= gr.short_description;
if(regex.test(strSD))
{
arr.push(strSD.toString());
}
}
gs.info(arr);

Remove bulk user passwords using encoded query in background script?

  • Hi, without additional filtering you would risk locking out all users including yourself.
  • Can you clarify the business drivers behind this requirement, as it is potentially a risk to BAU operations?
  • The script would be something like this, but I do not recommend running it in any environment.
var userQuery = new GlideRecord('sys_user');
userQuery.addEncodedQuery('active=true^user_password!=NULL')
userQuery.query();
while(userQuery.next()) {
    userQuery.user_password = '';
    userQuery.setWorkflow(false);
    userQuery.update();
}

SLA scnerio in background script?

Scenario :

In task_sla table task is “filed” This is a reference field to the incident now I want to pass incident table sys_id into task_sla table and check if the record is there in the table if the record is not there I want to print the incident number please help me anyone?

var gr = new GlideRecord('incident');
gr.query();
while (gr.next()){
	var taskGR = new GlideRecord('task_sla');
	taskGR.addQuery('task', gr.sys_id);
	taskGR.query();
	
	if (!taskGR.next()){
		gs.print('Incident ' + gr.number + ' not found in task sla table');
	}
}

How to Call client callable script include from Background Script?

getCallerLang: function(caller){
	var caller_id = JSUtil.nil(caller) ? this.getParameter('sysparm_caller_id') : caller;
}

Write a background script to remove duplicate CI’s In ServiceNow.

Scnerio:-

  • I want to remove all duplicates CIs using the background script.
  • I am new to servicenow can anyone please what the should be logic for that?
var dup = new GlideAggregate('<table name>');
dup.groupBy('<field name>');
dup.query();
while(dup.next()) {
	var dup1 = new GlideRecord('<table name>');
	dup1.addQuery('<field name>', dup.<field Name>);
	dup1.query();
	dup1.next();
	while(dup1.next())
		dup1.deleteRecord();
}

How to delete records from multiple tables using the Servicenow background script?

  • For multiple tables, just wrap your deletion script in a loop. Something like this. WARNING: UNTESTED CODE AHEAD!
(function () {
       var tableList = ['cmdb_ci', 'task', 'cmn_location', 'cmn_department' ];
       for (var i = 0; i < tableList.length; i++) {
                   var gr = new GlideRecord(tableName[i]);
                   gr.query();
                   gr.deleteMultiple()
;
       }
})();

ServiceNow background script to replace “author” in some KB articles

var obj= new GlideRecord('kb_knowledge');

obj.addEncodedQuery(query);   //Replace your query here              
obj.query();
gs.print(obj.getRowCount());

while(obj.next()){

obj.author= 'e6f8e8cb4f52320065fa4a318110c7f7';                                                              

obj.setWorkflow(false);
obj.update();
}

How to call script include function from script-background?

I have a simple script include function that I want to test from script background. I tried the scripts below, but it doesnt seem to be doing anything.

Script Include = UpdateTask

// try this in background script
var update = new UpdateTask(); update.eventMessage('sc_task','7','request_item.number','RITM0000001');

background script to Updated parent record from child record

var grChi = new GlideRecord("ast_service");//child record
grChi.addQuery("");//query goes here
grChi.query();
while (grChi.next()) { // updated grChil to grChi
   var grPar = new GlideRecord("ast_service");//parent record
   grPar.addQuery('sys_id',grChi.parent_contract); // updated this line
   grPar.query();
   if (grPar.next()){
      grPar.status = grChi.status;//update field on parent record
      grPar.update();
   }
}

How to update variable value using background script?

Scnerio:

  • I have to update the variable value on ritm and task form using the background script. Could you please help me with that?
  • Variable backend name ‘var_isInternational’ and I need to set ‘Yes or No’ value using background script.
try
{
var gr=new GlideRecord("sc_req_item");
gr.get("GIVE SYS_ID HERE");
gr.variables.var_isInternational="GIVE VALUE HERE"; //updated this line
gr.setWorkflow(false); //to stop BR's
gr.update();
}
catch(e)
{
gs.info("Error: "+e.message());
}

ServiceNow background script to close Open Requests, Requested Items, Tasks?

Scnerio: We have a request to “cleanup” old Requests where some of the RITMs are still open because some of the Tasks were never completed.  I’ve got a background script working all except for closing the Tasks.

ar SOURCE_REQUESTS = ['REQ0010027', 'REQ0010026','REQ0010011'];
var requestGR = new GlideRecord('sc_request');
requestGR.addQuery('number' , 'IN' , SOURCE_REQUESTS);
requestGR.setValue('state' , 4);
requestGR.setValue('request_state' , 'closed_incomplete');
requestGR.setValue('stage' , 'closed_incomplete');
requestGR.setValue('description' , 'Bulk closure of old tickets per SER0058621');
requestGR.setWorkflow(false);
requestGR.updateMultiple();
var requestItemGR = new GlideRecord('sc_req_item');
requestItemGR.addQuery('request.number' , 'IN' , SOURCE_REQUESTS);
requestItemGR.addActiveQuery();
requestItemGR.setValue('state' , 4);
requestItemGR.setValue('stage' , 'Request Cancelled');
requestItemGR.setWorkflow(false);
requestItemGR.updateMultiple();
var taskGR = new GlideRecord('sc_task');
taskGR.addQuery('request.number' , 'IN' , SOURCE_REQUESTS);
taskGR.addActiveQuery();
taskGR.setValue('state' , 4);
taskGR.setWorkflow(false);
taskGR.updateMultiple();

how to create a user using a background script?

how to create user using background script? using below conditions.

  • First we need to check if users exist or not, if user is exist not need to create and just update the role.
  • If users not exist then user has to create in users table and update the role
var user = new GlideRecord("sys_user");
user.addQuery("sys_id", user); // user is a variable which has a sys_id of the user which needs to be checked whether it exist or not
user.query();
if(user.next())
{
//update user roles
var roles = new GlideRecord("sys_user_has_role");
roles.initialize();
roles.roles = "282bf1fac6112285017366cb5f867469" // itil role sys_id
roles.user = user.sys_id;
roles.insert();
}
//else create a user record if user doesnt exist
var user1 = new GlideRecord("sys_user");
user1.initialize();
user1.user_name= username; // username is the variable which has the username of the new user
user1.first_name = user_firstname;
user1.insert();

Create a catalog request using cart API in background script?

var cartId = GlideGuid.generate(null);
var cart = new Cart(cartId);
var item = cart.addItem('9cb0a8e91b43f9107d619642b24bcba0');
cart.setVariable(item,'requested_for','3ded49fc978f79103579b811f053af70');
cart.setVariable(item,'group_approval','01f52aabdb827700ae2f16f35b961907');
var req = cart.placeOrder();

var ritm = new GlideRecord('sc_req_item');
ritm.addQuery('request', req.sys_id);
ritm.query();
if(ritm.next()){
	var arr = [];
	var mvrs = {};
	mvrs.group_approval = '01f52aabdb827700ae2f16f35b961907';
	arr.push(mrvs);
	ritm.variables.test_item_vset = JSON.stringify(arr);
	ritm.setWorkflow(false);
	ritm.update();
}

https://www.servicenow.com/community/developer-forum/background-script/m-p/2738414

Leave a Reply