Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

how to use array in background script

Anna_Servicenow
Tera Guru

In below script how can i use an array instead of single sys_id

var count = 0;
        var server = '9u99hvhft7800njhuy';
        var serverrel = new GlideRecord('cmdb_ci');
        serverrel.addEncodedQuery('parent.operational_status=1^child.sys_id=' + server);
        serverrel.query();
        while (serverrel.next()) {
            count++;
        }
        gs.log("count"+count);
        return JSON.stringify(count);

4 REPLIES 4

Samaksh Wani
Giga Sage

Hello @Anna_Servicenow 

 

use this :-

 

 var server = ['9u99hvhft7800njhuy', 'abc' 'xyz'];

 

Plz Mark my Solution as Accept and Give me thumbs up, if you find it Helpful.

 

Regards,

Samaksh

 

PRKK
Tera Contributor

Hello Anna,

 

you can use below script:

var servers =[1, 2, 3, 4, 5];

for(var i=0; i<servers.length; i++){

var serverrel = new GlideRecord('cmdb_ci');
        serverrel.addEncodedQuery('parent.operational_status=1^child.sys_id=' + servers[i]);
        serverrel.query();
        while (serverrel.next()) {
            count++;
        }

}

Ankur Bawiskar
Tera Patron
Tera Patron

@Anna_Servicenow 

what's your exact question?

you can do something like this

Also I optimized the script as there is no need of while since the only objective is to get the total count; you can use getRowCount()

var count = 0;
var server = ['sysId1','sysId2','sysId3'];
var serverrel = new GlideRecord('cmdb_ci');
serverrel.addEncodedQuery('parent.operational_status=1^child.sys_idIN' + server.toString());
serverrel.query();
count = serverrel.getRowCount();
gs.log("count"+count);
return JSON.stringify(count);

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Rahul Talreja
Mega Sage

@Anna_Servicenow ,
If you want query to run for multiple sys ID's, you actually dont need a array.
You can chnage your code accordingly:

var count = 0;
        var server = '9u99hvhft7800njhuy,<sys_id_2>,<sys_id_n>';
        var serverrel = new GlideRecord('cmdb_ci');
        serverrel.addEncodedQuery('parent.operational_status=1^child.sys_idIN' + server);
        serverrel.query();
        while (serverrel.next()) {
            count++;
        }
        gs.log("count"+count);
        return JSON.stringify(count);
Please mark my response correct/helpful as applicable!
Thanks and Regards,
Rahul