Service Catalog Group Add/Remove Item

Steve A
Kilo Expert

I am hoping to automate servicenow group management using a catalog item. The item will only be available to itil users based on the category available for: The request has a reference field for the usr and  reference field grp. The Approval process uses script to pull the group manager and if there is an error targets a specific Approval Error Override group. Currently the approval workflow path generates one catalog task to the servicenow admins. I would like to replace that with a script task. I have tried the following but it does not work and i am starting to think it is the write ACL on the sys_user_grmember table or maybe somethign I have overlooked in the script. We are using Service Portal as the only method for this request. Can I do this?

 

------------------------------------------- Workflow Script Action ---------------------------------

var usr = current.variables.user;
var grp = current.variables.group;
  if(!usr.isMemberOf(grp))
  {      
   var gr = new GlideRecord('sys_user_grmember');
   gr.query();
   gr.initialize();
   gr.user = usr;
   gr.group = grp;
   gr.insert();
}

1 ACCEPTED SOLUTION

Abhinay Erra
Giga Sage

Use this

var usr = current.variables.user;
var grp = current.variables.group;
if(!gs.getUser().getUserByID(usr).isMemberOf(grp)){     
   var gr = new GlideRecord('sys_user_grmember');
gr.initialize();
gr.user=usr;
gr.group=grp;
   gr.insert();
}

View solution in original post

5 REPLIES 5

Syvo
Mega Guru

Hi,

I guess usr.isMemberOf(grp) will result in an "undefined is not a function", because current.variables.user will not return a GlideUser object.

Try this instead:

var usr = current.variables.user.getValue();
var grp = current.variables.group.getValue();
var grGrMember = new GlideRecord('sys_user_grmember');
grGrMember.addQuery("user",usr);
grGrMember.addQuery("group",grp);
grGrMember.setLimit(1);
grGrMember.query();

if(!grGrMember.hasNext()) {      
   var gr = new GlideRecord('sys_user_grmember');
   gr.query();
   gr.initialize();
   gr.user = usr;
   gr.group = grp;
   gr.insert();
}

Note that this is untested 🙂 If it's not working, just add some gs.log to see what is going on.

Abhinay Erra
Giga Sage

Use this

var usr = current.variables.user;
var grp = current.variables.group;
if(!gs.getUser().getUserByID(usr).isMemberOf(grp)){     
   var gr = new GlideRecord('sys_user_grmember');
gr.initialize();
gr.user=usr;
gr.group=grp;
   gr.insert();
}

Hmm forgot about the getUserByID function, this answer is better.

Steve A
Kilo Expert

So clearly I have much to learn about servicenow and scripting. both of you were correct. I incorrectly assumed that a selected reference field variable could be used as a GlideUser object. Thank you Syvo for the clarification and thanks abhinay for the easy fix.