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.

while loop only executing for one record (background script)

Brian Arndt1
Mega Expert

Trying to develop a script to run as a background script to remove inherited itil roles from users who no longer need it (by virtue of their not having logged on for some time). The problem I'm having is that it works just fine with the inconvenient exception that it only removes the role from one user, even though multiple records are found.

The only clue I can find is that when I remove the line 'gr2.deleteRecord();' it does in fact complete the first loop through all records. But with that line in, it only runs through the first loop for one record. What am I missing?



gs.log('>>>BMA: starting process for usersNoLogin last 90 days');
var gr = new GlideRecord('sys_user_has_role');
gr.addQuery('role.name','itil');
gr.addQuery('user.active','true');
gr.addQuery('user.u_company_code', '!=', '0594').addOrCondition('user.u_company_code','');
gr.addQuery('user.last_login_time','<', gs.daysAgo(90)).addOrCondition('user.last_login_time','');
gr.query();
gs.log('>>>BMA: total number of usersNoLogin last 90 days: '+gr.getRowCount());

//initialize counter
var numberUpdated=0;

while(gr.next()){
var thisUserID = gr.user.sys_id;
var thisUserName = gr.user.user_name;
//get the groups the user is a member of
var gr2 = new GlideRecord('sys_user_grmember');
gr2.addQuery('user', thisUserID);
gr2.query();
//loop through all of the users groups
while(gr2.next()){
//make sure the group is not their public group
if(gr2.group!='c43c87bcff421000631771f4497efef1' &amp;&amp; gr2.group!='683ccbbcff421000631771f4497efefa'){
//delete the group membership
gs.log('>>>BMA: removing user '+thisUserName+' from group '+gr2.group.name);
gr2.deleteRecord();
numberUpdated++;
}
}
}
gs.log('>>>BMA: process for usersNoLogin last 90 days complete, '+numberUpdated+' records removed');

6 REPLIES 6

THANK YOU SO MUCH!!! I could not figure out why my fix script wasn't iterating properly through the while loop, but after I changed my 'gr' variable to a different name it is finally working!

If this answer is helpful please mark correct and helpful!

Regards,
Chris Perry

Thanks CapaJC! Changing "gr" to something else fixed my deleterecord while loop 🙂

regards, Peter