Servicenow add user to group using bg script

mail@pastecode.io avatar
unknown
javascript
a year ago
1.5 kB
8
Indexable
Never
var userGr = new GlideRecord("sys_user");
var grMemberGr = new GlideRecord("sys_user_grmember");

var KNOWLEDGE_CONTRIBUTOR_GROUP = "bbdce9631b8ea5108eb66575624bcb33";

// Query users in Knowledge Contributor Group
grMemberGr.addQuery("group", KNOWLEDGE_CONTRIBUTOR_GROUP);
grMemberGr.query();

// Store sys_id of grMembers that in the Knowledge Contributor group
var grMembers = [];

while(grMemberGr.next()){
    grMembers.push(grMemberGr.user.sys_id.toString());
}

userGr.addEncodedQuery("user_nameSTARTSWITHhr_agent");
userGr.query();

// Store sys_id of users that query from the sys_user table
var users = [];
while(userGr.next()){
    users.push(userGr.getUniqueValue().toString());
}

var usersToBeInserted = getInserted(users, grMembers);
gs.print(usersToBeInserted);

function getInserted(users, grMembers){
    // returns users that are not in grMembers
    var len = users.length;
    
    var result = [];
    for(var i = 0; i < len; i++){
        var user = users[i];

        // If a user is not in grMembers then add it to the result
        if(grMembers.indexOf(user) === -1)
            result.push(user);
    }

    return result;
}

// Add all users from usersToBeInserted to grMemberGr
do{
    var user = usersToBeInserted.pop();

    grMemberGr.initialize();
    grMemberGr.group = KNOWLEDGE_CONTRIBUTOR_GROUP;
    grMemberGr.user = user;
    grMemberGr.insert();
}while(usersToBeInserted.length != 0);