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.

Query to find Duplicate CIs by Name

anfield
Tera Guru

I have a query to run that will show me duplicate CI's by name (or serial if i modify slightly) in the cmdb_ci table. 

The background script below only returns the names of the CIs.

What I want is to return more columns, like status, operational status, created by.

How can I modify this to add the additional columns I want?

gs.print(getDuplicates('cmdb_ci','name'));

function getDuplicates(tablename,val) {
var dupRecords = [];
var gaDupCheck = new GlideAggregate(tablename);
gaDupCheck.addQuery('active','true');
gaDupCheck.addAggregate('COUNT',val);
gaDupCheck.addNotNullQuery(val);
gaDupCheck.groupBy(val);
gaDupCheck.addHaving('COUNT', '>', 1);
gaDupCheck.query();
while (gaDupCheck.next()) {
dupRecords.push(gaDupCheck[val].toString());
}
return dupRecords;
}

1 REPLY 1

joel_ruiz1
Tera Expert

You'll have to combine it with GlideRecord. Here is an example of getting both the CI's Name and Serial Number.

gs.print(getDuplicates('cmdb_ci','name'));

function getDuplicates(tablename,val) {
var dupRecords = [];
var gaDupCheck = new GlideAggregate(tablename);
gaDupCheck.addQuery('active','true');
gaDupCheck.addAggregate('COUNT',val);
gaDupCheck.addNotNullQuery(val);
gaDupCheck.groupBy(val);
gaDupCheck.addHaving('COUNT', '>', 1);
gaDupCheck.query();
while (gaDupCheck.next()) {

var gr = new GlideRecord("cmdb_ci");
gr.addQuery('name', gaDupCheck[val].toString());
gr.query();
while(gr.next()){

dupRecords.push(gr.name + ", " + gr.serial_number);

}
}
return dupRecords;
}

 

To get additional columns simple add gr.column_name to the string that's getting pushed in the dupRecords array.

 

Hope this helps!

 

-Joel R.