Script to Delete Roles from user roles

Chad Wilhelm1
Tera Expert

Hello,

I would like to delete a role hr approver from users based upon if they do not have the itil role.    The script below does not check to see if they have the itil role and when I add it I get no roles.   Any Suggestions?   Thanks!

var queryString = "role=2da3c4f8df93210068c37a0d3df26320";

var role = new GlideRecord('sys_user_has_role');

role.addEncodedQuery(queryString);
role.setLimit(1000);
role.query();

while (role.next()){

role.deleteRecord();

}

4 REPLIES 4

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

so you want users who don't have itil role for those hr approver role should be removed

so update code as below

query all users; for every user check whether that user doesn't have itil role in sys_user_has_role table

inside while loop check which record has hr approver role; delete that record

var gr = new GlideRecord('sys_user');
gr.query();
while(gr.next()){

var gr1 = new GlideRecord('sys_user_has_role');
gr1.addQuery('user', gr.sys_id);
gr1.addQuery('role','!=',itilRoleSysId);
gr1.query();
while(gr1.next()){

if(gr1.role == 'hrApproverRoleSysId')
gr1.deleteRecord();

}

}

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

You will need to replace the placeholders with the ITIL and HR role sys_id but try this script:

var user = new GlideRecord('sys_user');
user.query();
while (user.next()) {

    // Check if user has ITIL 
    var roleQuery = new GlideRecord('sys_user_has_role');
    roleQuery.addEncodedQuery("user=" + user.sys_id + "^role=itilRoleSysID");
    roleQuery.query();

    // If user does NOT have itil, delete the HR role record if it exists
    if(roleQuery.getRowCount() == 0) {
        var deleteQuery = new GlideRecord('sys_user_has_role');
        deleteQuery.addEncodedQuery("user=" + user.sys_id + '^role=HRRoleSysID');
        deleteQuery.query();
        if(deleteQuery.next()) {
            deleteQuery.deleteRecord();
        }
    }

}

Hello,

This did not work.   It deleted all the roles.

Thanks,

Chad

This was to the first reply.

I will try the script in 2nd.

Thanks,

Chad