Service Now - Add User to Group

Thursday Jan 9, 2020

Often we need to add a user to a group. This is a script that we can use in a business rule or something that can be called multiple times and will “do the right thing” and only add the user once…

Code

Here’s the code:

     /**
      * Copy fields from source to target. `fieldNames` key is the source field, the corresponding value is the target field name
      * 
      * fileNames[from] = to
      * 
      * @param {*} source GlideRecord
      * @param {*} target GlideRecord
      * @param {*} fieldNames {sourceField: targetField}
      */
     copyFieldValuesGlideRecordToGlideRecord: function(source, target, fieldNames) {
         var sourceFields = Object.keys(fieldNames);
         for (var i in sourceFields) {
             var sourceField = sourceFields[i];
             var targetField = fieldNames[sourceField];
             var targetElement = target.getElement(targetField);
             try {
                 target.setValue(targetField, (this.isReference(targetElement) &&
                     source.getValue(sourceField) != null ? source.getValue(sourceField).toString() : source.getValue(sourceField)));
             } catch (e) {
                 gs.error("Error copying field values: " + e);
                 throw (e);
             }
         }
     },
    simpleRecordAdd: function(table, recordData) {
            var ipGr = new GlideRecord(table);
            ipGr.initialize();
            this.copyObjectFieldsToGlideRecord(recordData, ipGr);
            return ipGr.insert();
    },
    doesRecordExist: function(table, fields, values) {
        var gr = new GlideRecord(table);
        for (var i = 0; i < fields.length; i++) {
            var field = fields[i];
            var value = values[i];
            gr.addQuery(field, value);
        }
        gr.query();
        return gr.next();
    },
    getRecord: function(table, fields, values) {
        var gr = new GlideRecord(table);
        for (var i = 0; i < fields.length; i++) {
            var field = fields[i];
            var value = values[i];
            gr.addQuery(field, value);
        }
        gr.query();
        if (gr.next()) {
            return gr;
        } else {
            throw (["Record does not exist in " + table + " for " + fields.join(", ") + " equal to " + values.join(", ")]);
        }
    },
    addUserToGroup: function(groupName, userSysId) {
        gs.debug("Trying to add [" + userSysId + "] to [" + groupName + "]");
        var group = this.getRecord("sys_user_group", ["name"], [groupName]);
        var groupSysId = group.getValue("sys_id").toString();

        gs.debug("Adding [" + userSysId + "] to [" + groupSysId + "]")
        if (this.doesRecordExist("sys_user_grmember", ["user", "group"], [userSysId, groupSysId])) {
            gs.debug("User already in group");
            return false;
        }
        var recordToAdd = {
            group: groupSysId,
            user: userSysId
        }
        if (this.simpleRecordAdd("sys_user_grmember", recordToAdd)) {
            gs.debug("Successfully added [" + userSysId + "] to [" + groupSysId + "]")
            return true;
        } else {
            throw ("Cannot add user to group - error saving record: " + JSON.stringify(recordToAdd));
        }
	}