Blog

GlideRecord Scripting

The most common and fundamental scripting used in ServiceNow is GlideRecord. Alter and reuse these scripts found in this post for your ServiceNow implementation.

Important Note: Always run GlideRecord statements in a development instance first and make sure they work correctly before using in production!

Server Side

Query

WHILE LOOP

This will return multiple records, because a while statement is used to cycle through the query results.

(function() {
grCI = new GlideRecord('cmdb_ci');
grCI.addQuery('sys_class_name','=','cmdb_ci_rack');
grCI.query();
while (grCI.next()){
gs.log('CI Found: '+grCI.name);
}
})();

IF STATEMENT

This will return one record, because a if statement is used to cycle through the query results. This is good if you just want to find one record, however the query would have returned seven items, which isn't completely efficent.

(function() {
var grIncident = new GlideRecord('incident');
grIncident.addQuery('priority','5');
grIncident.addQuery('category','inquiry');
grIncident.query();
if (grIncident.next()) {
gs.log('Incident Found: '+grIncident.number);
}
})();

SET LIMIT

The setLimit statement helps performance, because only one record is returned with the query.

(function() {
var grIncident = new GlideRecord('incident');
grIncident.addQuery('priority','5');
grIncident.addQuery('category','inquiry');
grIncident.setLimit(1);
grIncident.query();
if (grIncident.next()) {
gs.log('Incident Found: '+grIncident.number);
}
})();

ENCODED QUERY

Using an encoded query is often easier than multiple addQuery lines. You can also use Copy Query to help figure out your encoded query content which is helpful.

(function() {
var grIncident = new GlideRecord('incident');
grIncident.addEncodedQuery('priority=5^category=inquiry');
grIncident.query();
while (grIncident.next()) {
gs.log('Incident Found: '+grIncident.number);
}
})();

GET

it will return one record, because a get statement is used.

(function() {
    var grIncident = new GlideRecord('incident');
    grIncident.get('57af7aec73d423002728660c4cf6a71c');
    gs.log('Incident Found: '+grIncident.number);
})();

OR QUERY

Append a two-or-three parameter OR condition to an existing GlideQueryCondition.

I prefer to use an encoded query instead of this, but there are situations where this is easier.

(function() {
var grIncident = new GlideRecord('incident');
var qc = grIncident.addQuery('category', 'hardware');
qc.addOrCondition('category', 'network');
grIncident.query();
while (grIncident.next()){
gs.log('Incident Found: '+grIncident.number);
}
})();

INSERT

(function() {
var grIncident = new GlideRecord('incident');
grIncident.initialize();
grIncident.short_description = 'www.servicenowelite.com';
grIncident.category = 'network';
grIncident.subcategory = 'dns';	
grIncident.contact_type = 'email';
grIncident.caller_id.setDisplayValue('Fred Luddy');
grIncident.insert();
gs.log('Incident created: '+grIncident.number);
})();

UPDATE

UPDATE

If you are doing an update statement in your script, it is good to be extra careful.  Comment out your update statement and add a log statement to check the script for accuracy before actually using it.

(function() {
grCI = new GlideRecord('cmdb_ci');
grCI.addQuery('name','=','SAP WEB03');
grCI.query();
gs.log('grCI Query: ' + grCI.getEncodedQuery() + ' = ' + grCI.getRowCount());
while (grCI.next()){
grCI.comments='ServiceNowELITE.com';
//grCI.update;
}
})();

setWorkflow(false) and autoSysFields(false)

When you are mass updating records, sometimes you don't want to run the business rules/workflow on every record you updated or have your name and the last updated time be when you updated it.  Here is an example on how to avoid this:

(function() {
grCI = new GlideRecord('cmdb_ci');
grCI.addQuery('name','=','SAP WEB03');
grCI.query();
gs.log('grCI Query: ' + grCI.getEncodedQuery() + ' = ' + grCI.getRowCount());
if (grCI.next()){
grCI.comments='ServiceNowElite.com';
grCI.setWorkflow(false); //Do not run business rules
grCI.autoSysFields(false); //Do not update system fields
//grCI.update;
}
})();

DELETE

If you are doing an delete statement in your script, it is good to be extra careful.  Comment out your delete statement and add a log statement to check the script for accuracy before actually using it.

(function() {
var grComputer = new GlideRecord("cmdb_ci_computer");
grComputer.addEncodedQuery('sys_created_by=mikekaufman')
grComputer.query();
gs.log('grComputer Query: ' + grComputer.getEncodedQuery() + ' = ' + grComputer.getRowCount());
var deleteCount = 0;
while(grComputer.next()){
grComputer.setWorkflow(false);
//grComputer.deleteRecord();
deleteCount++;
}
gs.log('Records Deleted: '+ deleteCount);
})();

Client Side

You can use similar GildeRecord scripts on the client side, except you should enclose them in a GlideAjax Query

In the example below, it uses a Script Include and Client Script to set the Department field on a form based on the Requested For user.

Script Include

Name: SNEClientUtil
Client Callable: True
Scope: All application scopes
Script:
var SNEClientUtil = Class.create();
SNEClientUtil.prototype = Object.extendsObject(AbstractAjaxProcessor, {
	getUserInfo : function() {
		var usr = this.getParameter('sysparm_user');
		var obj = {};
		var gr = new GlideRecord('sys_user');
		gr.addQuery('sys_id', usr);
		gr.query();
		if(gr.next()) {
			obj.phone = gr.phone.toString();
			obj.email = gr.email.toString();
			obj.mobile_phone = gr.mobile_phone.toString();
			obj.department = gr.department.sys_id.toString();
			obj.manager = gr.manager.sys_id.toString();
			obj.location = gr.location.sys_id.toString();
		}
		var json = new JSON();
		var data = json.encode(obj);
		return data;
	},
	type: 'SNEClientUtil'
});

Client Script (ON LOAD)

Name: Set User Info
Applies to: A Catalog Item
Type: onLoad
UI Type: All
Applies on a Catalog Item view: true
Script:
function onLoad() {
	var ga = new GlideAjax('global.SNEClientUtil');
	ga.addParam('sysparm_name', 'getUserInfo');
	ga.addParam('sysparm_user', g_form.getValue('requested_for'));
	ga.getXML(processAnswer);
}
function processAnswer (response)  {
	var answer = response.responseXML.documentElement.getAttribute("answer");
	var obj = JSON.parse(answer);
	g_form.setValue('department', obj.department);
}

CLIENT SCRIPT (ON CHANGE)

Name: Set User Info
Applies to: A Catalog Item
Type: onChange
Variable Name: requested_for
UI Type: All
Applies on a Catalog Item view: true
Script:
function onChange(control, oldValue, newValue, isLoading) {
	if (isLoading) {
      return;
   }
		
	
	if (newValue == '') {
		g_form.setValue('department', '');
	}
	var ga = new GlideAjax('global.SNEClientUtil');
	ga.addParam('sysparm_name', 'getUserInfo');
	ga.addParam('sysparm_user', g_form.getValue('requested_for'));
	ga.getXML(processAnswer);
}
function processAnswer (response)  {
	var answer = response.responseXML.documentElement.getAttribute("answer");
	var obj = JSON.parse(answer);
	g_form.setValue('department', obj.department);
}