This article is a supplement to the ServiceNow documentation. For full documentation please refer ServiceNow official website
Checkout our NEW Video Channel you can like and subscribe too!

Introduction

It is always good to refer scripts when we are in a deadline to complete our assignments. Below I list few useful script that I use for myself.This sample ServiceNow scripts are randomly chosen and doesn’t related to one another. They demonstrate real-life scenarios so hope it will be helpful for you too.

Create Problem for P1 & P2 Incident

Here we need to write a Business rules

table129102019.PNG

create probelm for p1 inc29102019.PNG

Advanced script

(function executeRule(current, previous /*null when async*/ ) {

    var prob = new GlideRecord("problem");
    prob.short_description = current.short_description;
    prob.description = current.description;
    prob.impact = current.impact;
    prob.urgency = current.urgency;
    prob.cmdb_ci = current.cmdb_ci;
    prob.u_primary_affected_site = current.u_primary_affected_site;
    prob.priority = current.priority;
    prob.company = current.company;
    prob.u_problem_type = "reactive";

    // JObi added here 

    prob.parent = current.sys_id;
    prob.u_category = current.category;
    prob.u_subcategory = current.subcategory;
    //prob.sys_domain = current.sys_domain;
    prob.assignment_group = current.assignment_group;
    prob.u_incident_id = current.sys_id;
    prob.assigned_to = current.assigned_to;
    prob.state = 8;
    var sysID = prob.insert();

    current.problem_id = sysID;
    //var mySysID = current.update();
    gs.addInfoMessage("Problem " + prob.number + " created");

})(current, previous);

Send sms for P1 & P2 closure

Here we need to write a Business rules

table129102019.PNG

send sms for P1 & P2 closure 29102019.PNG

Advanced script

(function executeRule(current, previous /*null when async*/) {

	var recipient = "";
	var site = "u_opco=Global^ORu_opco=" + current.u_primary_affected_site;
	recipient = recipient + "919000000"+","+ "911111111";
	var priority;
	if(current.priority == 1)
		priority = "P1";
	else if(current.priority == 2)
		priority = "P2";
	var short_message = "Hi All, Incident " + current.number + " with short description as " + current.short_description + " has been resolved in ServiceNow" ;
	short_message = short_message + " Details of the Incident are below: \n";
	var msg = "Status : "+ current.state.getDisplayValue() + "\n" + "Reported by : "+ current.caller_id.getDisplayValue() + "\n" + "Priority : "+ current.priority.getDisplayValue() +"\n"  + "Reported Time : " + current.sys_created_on + "\n" +"Resolved Time : "+ current.resolved_at + "\n"+ "Description : "+ current.description +"\n";
short_message = short_message + " " + msg;	
	try { 
 var s = new sn_ws.SOAPMessageV2('SMS_ECP', 'SMSSubmit');
 s.setStringParameterNoEscape('Recipient.SegmentList', '');
 s.setStringParameterNoEscape('Tariff.TariffCode', '');
 s.setStringParameterNoEscape('Sender.SenderAddressType', '');
 s.setStringParameterNoEscape('Recipient.DistributionListID', '');
 s.setStringParameterNoEscape('MsgDetails.ValidityPeriodDateTime', '');
 s.setStringParameterNoEscape('Sender.Address', '30379');
 s.setStringParameterNoEscape('Tariff.TariffPrice', '');
 s.setStringParameterNoEscape('Recipient.Number', recipient);
 s.setStringParameterNoEscape('MsgDetails.ShortMessage', short_message);
 s.setStringParameterNoEscape('Sender.Password', 'WiP@!254');
 s.setStringParameterNoEscape('req.InterfaceType', 'SOAP');
 s.setStringParameterNoEscape('Sender.Username', 'WiprokeS');
 s.setStringParameterNoEscape('DeliveryReport.ReportEnabled', '');
 s.setStringParameterNoEscape('MsgDetails.ScheduledDeliveryDateTime', '');
 s.setStringParameterNoEscape('MsgDetails.MsgType', '0');
 var response = s.execute();
var responseBody = response.getBody(); 
var status = response.getStatusCode();
	//gs.addInfoMessage(status);
}
catch(ex) { 
 var message = ex.message;
}

})(current, previous);

Populate Problem due date

Here we need to write a Business rules

table229102019.PNG

Populate Problem due date29102019.PNG

Advanced script

(function executeRule(current, previous /*null when async*/) {
	var gdt = new GlideDateTime(current.u_expected_closure_date);	
    current.due_date = gdt.getDate();
	var dateDueDate = current.due_date;
    var dueDate = new GlideDateTime(dateDueDate);
    var arrDate = [];
    arrDate = dueDate.toString().split(' ');
    current.due_date.setDisplayValue(arrDate[0]+ ' 23:59:59','yyyy-MM-dd HH:mm:ss'); 
})(current, previous);

To prevent null userids to be inserted

Here we need to write a Business rules

To prevent null userids to be inserted29102019.PNG

Advanced script

if ((current.user_name == "null") || (current.user_name == "NULL") || (current.user_name == "")) {
    current.setAbortAction(true);
}
if (((current.first_name == "null") || (current.first_name == "NULL") || (current.first_name == "")) 
    && ((current.last_name == "null") || (current.last_name == "NULL") || (current.last_name == ""))) {
    current.setAbortAction(true);
}

Make change task mandatory

Here we need to write a Business rules

Make change task mandatory29102019.PNG

Advanced script

Make change task mandatory229102019.PNG

var gr = new GlideRecord('change_task');
gr.addQuery('parent', current.sys_id);
gr.query();
if (gr.getRowCount() == 0) {
    gs.addErrorMessage('Kindly Add atleast one Change task to move the Change to Assess State');
    current.state = "-5";
    //current.setAbortAction(true);
}

Autopopulate 1st Manual Communication

Here we need to write a Business rules

Autopopulate 1st Manual Communication.PNG

Advanced script

Autopopulate 1st Manual Communication2.PNG

(function executeRule(current, previous /*null when async*/ ) {

    var gr = new GlideRecord('incident');
    gr.addQuery('number', current.instance.number);

    gr.query();
    if (gr.next()) {

        var manual_comm_value = gr.u_manual_communication;

        if (manual_comm_value == '') {
            gr.u_manual_communication = current.sys_created_on;
            gr.update();

        }

    }

})(current, previous);

Update parent_incident_is_closed in problem table if parent incident in incident table is closed

Here we need to write a Business rules

update parent incident is closed 29102019.PNG

Advanced script

(function executeRule(current, previous /*null when async*/ ) {

    if (current.state == '7') {

        var gr = new GlideRecord('problem');
        gr.addQuery('sys_id', current.problem_id);
        gr.query();
        while (gr.next()) {
            gr.u_parent_incident_is_closed = true;
            gs.log("parent incident checkbox value" + gr.u_parent_incident_is_closed);
            gr.update();
        }
    }

})(current, previous);

Comments Mandatory For request item

Here we need to write a Business rules Comments Mandatory For request item29102019.PNG

Advanced script

Comments Mandatory For request item229102019.PNG

(function executeRule(current, previous /*null when async*/ ) {

    var gr = new GlideRecord('sc_req_item');
    gr.addQuery('sys_id', current.document_id);
    gr.query();
    if (gr.hasNext() && (current.state == 'approved' || current.state == 'rejected')) {
        var v1 = current.comments.getJournalEntry(-1);
        if (v1 == '') {
            gs.addErrorMessage("Please provide comments before approving/rejecting");
            current.setAbortAction('true');
        }
    }

})(current, previous);

Close child task before resolving Incident

Here we need to write a Business rules

Close child task before resolving Inc29102019.PNG

Advanced script

(function executeRule(current, previous /*null when async*/ ) {

    var gr = new GlideRecord('incident_task');
    gr.addQuery('incident', current.sys_id);
    gr.addQuery('active', 'true');
    gr.query();
    if (gr.next()) {
        current.setAbortAction();
        gs.addErrorMessage("Please resolve all the Incident task before closing the Incident");
    }
  
})(current, previous);

RCA Attachment Check

Here we need to write a Business rules

RCA Attachment Check29102019.PNG

Advanced script

(function executeRule(current, previous /*null when async*/ ) {

    var isAttach = new GlideRecord('sys_attachment');
    isAttach.addQuery('table_name', 'problem');
    isAttach.addQuery('table_sys_id', current.sys_id);
    isAttach.query();
    if (!isAttach.hasNext()) {
        gs.addInfoMessage("Please attach the RCA document in order to move the state to Approval");
        current.state = previous.state;
        current.problem_state = previous.problem_state;
        current.setAbortAction(true);
    }

})(current, previous);

Removing role on user deactivation

Here we need to write a Business rules Removing  role on user deactivation29102019.PNG

Advanced script

(function executeRule(current, previous /*null when async*/ ) {

    //removes all role from user when user is deactivated
    var userroleremove = new GlideRecord('sys_user_has_role');
    userroleremove.addQuery('user', current.sys_id);
    userroleremove.query();
    while (userroleremove.next()) {
        //gs.log('inside while');

        userroleremove.deleteRecord();
    }

    //Removing approver_user role from user manager incase he is not a manager of  anyother user when user is deactivated
    if (current.manager != '') {
        var prevuser = new GlideRecord('sys_user');
        prevuser.addQuery('active', 'true');
        prevuser.addQuery('manager', current.manager);
        prevuser.query();
        if (prevuser.next()) {

        } else {
            var userrole = new GlideRecord('sys_user_has_role');
            userrole.addQuery('user', current.manager);
            userrole.addQuery('role.name', 'approver_user');
            userrole.query();
            if (userrole.next()) {

                userrole.deleteRecord();
            }

        }
    }

})(current, previous);

Feedback KB Update Review KA

Here we need to write a Business rules

Feedback KB Update Review KA29102019.PNG

Advanced script

(function executeRule(current, previous /*null when async*/ ) {

    // Add your code here
    //glide record on the kb table set the u_review_ka to true
    // call the event (knowledge.feedback) to notify the manager

    var gr = new GlideRecord('kb_knowledge');
    gr.addQuery('sys_id', current.article);
    gr.query();
    if (gr.next()) {
        //gs.log('**************' +gr.number);
        gr.setValue('u_review_ka', true);
        gr.update();
        //gs.eventQueue('knowledge.feedback',gr,'','');
    }
})(current, previous);

Notuseful KB Update Review KA

Here we need to write a Business rules

Not Useful KB Update Review KA29102019.PNG

Advanced script

(function executeRule(current, previous /*null when async*/ ) {

    // Add your code here
    //glide record on the kb table set the u_review_ka to true
    // call the event (knowledge.notuseful) to notify the manager 
    var gr = new GlideRecord('kb_knowledge');
    gr.addQuery('sys_id', current.article);
    gr.query();
    while (gr.next()) {
        //gs.log('**************' +gr.number);
        gr.setValue('u_review_ka', true);
        gr.update();

        //gs.eventQueue('knowledge.notuseful',gr,'','');
        var manager = new ReturnManagerGroupKnowledge().managergroup();
        gs.log('aritra' + v1);

        var userList = [];
        var userRec = new GlideRecord('sys_user_grmember');
        userRec.addQuery('group', manager);
        userRec.query();
        while (userRec.next()) {

            if (userList.toString().indexOf(userRec.sys_id) == -1) {
                userList.push(userRec.user + "");
            }
        }
        var v1 = current.author;
        var v2 = userList.toString();
        gs.log("emails   " + v2);

        gs.eventQueue('knowledge.notuseful', current, v2);*/

    }
})(current, previous);

Run the KA Publish Workflow

Here we need to write a Business rules Run the KA Publish Workflow29102019.PNG

Advanced script

(function executeRule(current, previous /*null when async*/ ) {

    startKnowledgeApprovalkWorkflow();

    function startKnowledgeApprovalkWorkflow() {

        var wf = new GlideRecord("wf_workflow");
        if (!wf.get("name", "AA Knowledge Approval Publish"))
            return;
        var w = new Workflow();
        w.startFlow(wf.sys_id, current, current.operation());
    }

    gs.log("Workflow trigerred1");

    startWorkflow('bf7f13ffdb90ff406ac4e2a94b961930');

    function startWorkflow(id) {
        var wf = new Workflow().getRunningFlows(current);
        if (!wf.next()) {
            var context = new global.Workflow().startFlow(id, current, '', '');
            wf = new global.Workflow();
            var wfId = wf.getWorkflowFromName("AA Knowledge Approval Publish");
            wf.startFlow(wfId, current, '', '');
            gs.log("Workflow trigerred2");
        }
    }

})(current, previous);
    Content