Scheduled job Script

soraya_vally
Mega Guru

Hi Community, 

 

I need to create a script to check users that are inactive for the last 7 days and remove them from any roles and groups. I do not want to delete any user, only remove there ITIL license and groups they are part of. 

 

I need to print the user name and group they were removed from as well.

 

Please assist with the script, I need to run this as a background script first before creating the schedule. 

 

 

2 REPLIES 2

Anil Lande
Kilo Patron

You can use flow designer instead.

Please check below link:

https://www.servicenow.com/community/itsm-forum/how-to-automatically-remove-a-user-who-is-inactive-f...

 

Please appreciate the efforts of community contributors by marking appropriate response as correct answer and helpful, this may help other community users to follow correct solution in future.
Thanks
Anil Lande

Amit Verma
Kilo Patron
Kilo Patron

Hi @soraya_vally 

 

You can make use of below logic to check the users who are inactive from the last 7 days, remove them from all the groups and remove all their user roles as well.

 

var grSysUser = new GlideRecord('sys_user');
grSysUser.addEncodedQuery("active=false^sys_updated_onRELATIVEGT@dayofweek@ago@7"); //You can use Updated On field or Last Login field accordingly.
grSysUser.query();
while (grSysUser.next()) {
// Remove User from All Groups
var gr = new GlideRecord('sys_user_grmember');
gr.addQuery('user',grSysUser.sys_id);
gr.query();
while (gr.next()) {
gr.deleteRecord();
gs.info('user ' + grSysUser.name + ' removed from group ' + gr.group.name + ' due to being deactivated');
}

// Remove all Roles from the user
var grRole = new GlideRecord('sys_user_has_role');
grRole.addQuery('user',grSysUser.sys_id);
grRole.query();
while(grRole.next()){
	grRole.deleteRecord();
	gs.info('User '+ grSysUser.name + 'role '+ grRole.role + 'removed due to inactivity');
}
}

 

Thanks & Regards

Amit Verma


Please mark this response as correct and helpful if it assisted you with your question.