VaranAwesomenow
Mega Sage

Takes input as table name , column name in table that has reference to user and role name.

This script provides gives an output of sys ids that have a specific role.

var tableName = 'cmdb_ci_business_app';
var userCloumnName = 'it_application_owner';
var roleName = 'cmdb_read';
var userHash = {};
var grApp = new GlideRecord(tableName);
grApp.query();
while (grApp.next()) {
userHash[grApp[userCloumnName]] = 1;
}
getUserList(userHash);

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;
}