- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
07-01-2019 07:06 AM
Hi ,
I have already old 600 inactive users .How to remove roles and Groups for those inactive users.I tried to create schedule job But it is not running .
Can you please suggest me .
Solved! Go to Solution.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
07-01-2019 07:14 AM
Hi,
You could use this in a background script to remove the groups.
var gr = new GlideRecord('sys_user');
var gr2 = new GlideRecord('sys_user_grmember');
gr.addQuery('active', false);
gr.query();
while (gr.next()) {
gr2.addQuery('user', gr.sys_id);
gr2.query();
while (gr2.next()) {
gr.deleteMultiple();
}
}
This would query for an inactive user, if found, query if they are a member of any groups, if found - delete all membership(s), then moves on to the next user. Keep in mind, this could run for a bit so be mindful when you're doing this.
Now if roles were assigned to users as well (which isn't best practice) ...then you can use this same script but then switchout sys_user_grmember with sys_user_has_role and run it again.
Please mark reply as Helpful/Correct, thanks!
Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-13-2022 12:02 PM
For some reason, the second loop doesn't correctly query the groups the user is in. The script that did work for me was this. You can access the user reference in sys_user_grmember table and filter inactive users. To check, you can comment out the deleteRecord() function and have it print out the record and verify it with your view list in servicenow.
// Remove user from groups
var ar = new GlideRecord('sys_user_grmember');
ar.addEncodedQuery('user.active=false');
ar.query();
while(ar.next()) {
// gs.print(ar.email);
ar.deleteRecord();
}
Also, if required, you can run another script that will remove user roles from an inactive user that are NOT inherited from groups. Again you can verify this in servicenow by going to navigation and typing in sys_user_has_role.list
// Remove user_roles from users
var gr = new GlideRecord('sys_user_has_role');
gr.addEncodedQuery('user.active=false^inherited=false');
gr.query();
while(gr.next()) {
gr.deleteRecord();
}
Hope this helps
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-14-2023 02:31 PM
This script will delete all the groups in your instance so be weary of this. Running the background script caused me to have to undo the deleted sys_user_group records in our dev instance.