background script to remove duplicate CI's

--oooo--
Tera Contributor

hello Experts,

I want to remove all duplicates CI's using background script.

I am new to servicenow can anyone please what should be logic for that.

Thank You.

1 ACCEPTED SOLUTION

 

Try this, please test this with few examples before running it against the full table

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();
}
-Anurag

View solution in original post

4 REPLIES 4

Anurag Tripathi
Mega Patron
Mega Patron

Hi,

Here is a sample script to identify duplicates, Pass the table and the field you want to search duplicates on.

gs.print(getDuplicates('<table Name>','<field name>')); //pass the field name and table name here
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;
}

 

-Anurag

--oooo--
Tera Contributor

Hello @Anurag Tripathi if cmdb_ci table contain any duplicate CI's i want to remove that .i don't want to fetch duplicates CI's. please guide me on this.

thank you

 

 

Try this, please test this with few examples before running it against the full table

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();
}
-Anurag

--oooo--
Tera Contributor

Hello @Anurag Tripathi, I have written code by taking your script reference but cannot fetch duplicate CIs. please guide me, what am doing wrong here? thank you.

gs.print(getDuplicates('cmdb_ci_computer','asset_tag')); //pass the field name and table name here
function getDuplicates(cmdb_ci_computer,asset_tag) {
var dupRecords = [];
var gaDupCheck = new GlideAggregate(cmdb_ci_computer);
gaDupCheck.addQuery('active','true');
gaDupCheck.addAggregate('COUNT',asset_tag);
gaDupCheck.addNotNullQuery(asset_tag);
gaDupCheck.groupBy(asset_tag);
gaDupCheck.addHaving('COUNT', '>', 1);
gaDupCheck.query();
while (gaDupCheck.next()) {
dupRecords.push(gaDupCheck[asset_tag].toString());
}
return dupRecords;
gs.print(dupRecords);
}