CI mass deletion using background script

jiral
Giga Sage

We have about a number of duplicate CIs which we set on "Archived" status to know that they are duplicate and we want to delete them. Using a background script I want to delete these duplicate CIs meeting the following conditions:

1. Status is Archived

2. Class is either Network Gear OR IP Switch OR Router

3. In cmbd_ci table

  1. var duplicate = new GlideRecord('cmdb_ci');  
  2. duplicate.addQuery('install_status','=', '200');
  3. duplicate.addQuery(('sys_class_name','=', 'cmdb_ip_switch')||('sys_class_name','=','cmdb_ci_ip_router')||('sys_class_name','=', 'cmdb_ci_netgear'));
  4. duplicate.query();  
  5. while (duplicate.next()) {    
  6. gs.log('Deleted Duplicate CIs ' + duplicate.number + ' deleted');  
  7. duplicate.deleteRecord();  
  8. }  

Can you inspect the script above for issues before I run this against the cmdb_ci table?

1 ACCEPTED SOLUTION

You'll get a bit better performance with this:



var duplicate = new GlideRecord('cmdb_ci_netgear');    


duplicate.addQuery('install_status','=', '200');    


duplicate.deleteMultiple();    



GlideRecord - ServiceNow Wiki


View solution in original post

7 REPLIES 7

Chuck Tomasi
Tera Patron

Hi Jeffiral,



I recommend building an encoded query from the list and using that in your query. You might find it faster to use the deleteMultiple() method instead of using the while loop and doing a deleteRecord() on each record as well.



Regarding the encoded query, you might find this short video helpful.



Video: Scripting Complex Queries Quickly


snowenthusiast
Tera Contributor

Hi jeffiral,



Since Routers and Switches fall under network gear, you can simply do:



var duplicate = new GlideRecord('cmdb_ci_netgear');      


duplicate.addQuery('install_status','=', '200');      


duplicate.query();


           


while (duplicate.next()) {        


        gs.log('Deleted Duplicate CIs ' + duplicate.number + ' deleted');      


        duplicate.deleteRecord();      


}      



Hope this helps.


You'll get a bit better performance with this:



var duplicate = new GlideRecord('cmdb_ci_netgear');    


duplicate.addQuery('install_status','=', '200');    


duplicate.deleteMultiple();    



GlideRecord - ServiceNow Wiki


bernyalvarado
Mega Sage

Hi Jeffiral,



A couple of additional advices:



a) Make sure you run that routine as an onDemand scheduled job. That's often the best way to run very heavy routines that need to delete data (specially within the CMDB with so many relationships and cascade deletes)


b) Try testing the routine in a SubProduction instance first and validate it worked as expected.



Wish you a smooth deletion! Hope this helps.



Thanks,


Berny