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.

Removing Invalid References

jamesmcwhinney
Giga Guru

Somewhere along the way, we ended up with a number of users linked to groups which no longer exist.

In the user's profile underneath groups, I see a long list of blank entries.

Could anyone reccomend a good script to clear out entries in a table wherein the reference does not exist.

For example, something along the lines of:

Delete * from sys_user_grmember where group not in (select sys_id from sys_user_group)

Thanks!

1 ACCEPTED SOLUTION

jamesmcwhinney
Giga Guru

This seems to be giving me what I need.


I will use this along with deleteMultiple()





var gr = new GlideRecord('sys_user_grmember');


gr.addEncodedQuery('group.nameISEMPTY');


gr.query();


gs.log("Final Count: " + gr.getRowCount());


View solution in original post

8 REPLIES 8

Abhinay Erra
Giga Sage

var gr= new GlideRecord('sys_user_grmember');


gr.query();


while(gr.next()){


var gr1=new GlideRecord('sys_user_group');


gr1.addQuery('sys_id',gr.group);


gr1.query();


if(gr1.next()){


}


else{


gr.deleteRecord(); // be careful while using this statement, I recommend to use gs.print() in the background scripts first and see if it is pulling the correct records


}


}


venkatiyer1
Giga Guru

I would recommend adding an active check to the first query and also modifying the code to check for active flag



var gr = new GlideRecord("sys_user_grmember");


gr.addActiveQuery();


gr.query();


while (gr.next()) {


  var grGroup = new GlideRecord("sys_user_group");


  grGroup.get(gr.group.sys_id);


  if(!grGroup.active) {


  gr.deleteRecord();


  }


}


It seems to only delete the first record and then gets kicked out of the loop...


Any idea why?


And is there a way to do this using deletemultiple() so that it is more performance friendly?