Find a set of users that have a specific role
function getUserList(userIdHash) { var userHashNew = {}; for (var userId in userIdHash) { // use hasOwnProperty to filter out keys from the Object.prototype if (userIdHash.hasOwnProperty(userId)) { //gs.print(userId); var hasRoleOnlyBol = hasRoleOnly('cmdb_read', userId); // role name can be any role // gs.print(userId + " " + hasRoleOnlyBol); if (hasRoleOnlyBol) { userHashNew[userId] = 1; } } } printUserList(userHashNew);
}
function printUserList(userHash) { var outputString = ''; for (var userId in userHash) { // use hasOwnProperty to filter out keys from the Object.prototype if (userHash.hasOwnProperty(userId)) { outputString += userId + "\n"; } } gs.print(outputString);
}
function checkRole(userId) { //gs.print(JSUtil.type_of(userId)); var grUser = new GlideRecord('sys_user'); grUser.get(userId); // gs.print(JSUtil.type_of(grUser)); if (grUser.hasRole(roleName) && !grUser.hasRole('itil')) { gs.print("insideIf"); return true; } else { return false; }
}
function hasRoleOnly(roleName, userId) { var returnBol = false; var roleList = getAllRoles(userId); if (roleList.length() > 1 || roleList.length == 0 || JSUtil.nil(roleList)) { returnBol = false; } if (roleList.length == 1) { if (roleName == roleList[0]) { returnBol = true; } } return returnBol;
}
function getAllRoles(userId) { var roleList = []; var grUserRole = new GlideRecord('sys_user_has_role'); var query = 'user=' + userId; grUserRole.addEncodedQuery(query); grUserRole.query(); while (grUserRole.next()) { roleList.push(grUserRole.role.name); } return roleList;
}
Labels:
https://www.servicenow.com/community/now-platform-blog/find-a-set-of-users-that-have-a-specific-role/ba-p/2291918