Removing Roles of Inactive users

Mason5
Mega Expert

Hi All,

I am trying to remove all roles of users(from sys_user_has_role) who are inactive and locked out in user table but it does not allow to remove records from sys_user_has_role table, does not delete with Background script as well.

How can we achieve this, any idea?

Thanks in Advance!

1 ACCEPTED SOLUTION

Hi Mason,

ensure you wrap code inside function

updateRecord();

function updateRecord(){

try{

var gr = new GlideRecord('sys_user_has_role');
gr.addEncodedQuery('user.locked_out=true^user.active=false');

gs.info('Row Count is: ' + gr.getRowCount());

gr.query();
while(gr.next())
{
gr.deleteRecord();
}
}

catch(ex){
gs.info('Exception is: ' + ex);
}

}

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

21 REPLIES 21

Hi Mark,

Tried but did not work unfortunately. Just executed code in backgrounds script. Tried deleteRecord() deleteMultiple()

Hello Mike,

Actually just noticed, it is not allowing to delete those roles which are inherited from Groups, tried to create a user and separately assigned  roles to that user and I could delete those roles.

But my requirement is to delete those roles which are inherited from Group, can we do anything with this, please?

 

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Mason,

please share background script you tried

I tried this and it worked

var gr = new GlideRecord('sys_user_has_role');
gr.addQuery('sys_id','5152bd22db7433009f7890b6db96199b'); // sys_id of the record
gr.query();
if(gr.next()){
gr.deleteRecord();
}

If my answer solved your issue, please mark my answer as Correct & 👍Helpful based on the Impact.

Regards
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Hi Ankur,

Below is the script I tried,

var gr = new GlideRecord('sys_user_has_role');
gr.addEncodedQuery('user.locked_out=true^user.active=false');
gr.query();
while(gr.next())
{
gr.deleteRecord();
// gr.deleteMultiple(); //Tried this as well
}

 

If going for code like this, don't go for a while + gr.deleteRecord. This performs awefull. Have a look at the example I posted earlier.

If my answer helped you in any way, please then mark it as helpful.

Kind regards,
Mark
2020 ServiceNow Community MVP
2020 ServiceNow Developer MVP

---

LinkedIn
Community article list

 

Kind regards,

 

Mark Roethof

Independent ServiceNow Consultant

10x ServiceNow MVP

---

 

~444 Articles, Blogs, Videos, Podcasts, Share projects - Experiences from the field

LinkedIn