How to add and remove a user to a local ServiceNow group through a workflow script

Colby Brunner
Giga Contributor

I have a fairly simple request, but I am not familiar with developing so I was hoping someone could point me in the right direction.

I want to automate the provisioning of admin users in ServiceNow by requiring users to request admin access each time. One user will request this access for themself, and 8 hours later, they will be automatically removed.

The group will be the same every time; it's one user being assigned to one group.

I have a local ServiceNow group that I can add users to using the below script:

var groupQuery = new GlideRecord('sys_user_grmember');
groupQuery.initialize();
groupQuery.user = current.variables.requested_for; //whatever your current user field is
groupQuery.group = "aab64544db59581000c4fef86896192a";
groupQuery.insert();

It adds the user without issue, but I am not able to remove the one group for the user after the time is reached. I either don't remove the group at all, or I remove all groups for the user.

Below is the code I have to remove the user, but I could be completely wrong here:

var gr = new GlideRecord('sys_user_grmember');
gr.addQuery('group','aab64544db59581000c4fef86896192a');
gr.addQuery('user','current.variables.requested_for');
gr.query();
gr.next();
gr.deleteRecord();

Please let me know how I can modify this script to remove the one user from the ServiceNow Admin Access group.

1 ACCEPTED SOLUTION

Allen Andreas
Administrator
Administrator

Hi,

This line can be adjusted as:

gr.addQuery('user',current.variables.requested_for);

and remaining script like:

gr.query();
if (gr.next()) {
gr.deleteRecord();
}

This is assuming your sys_id for the group is correct and there is a variable called requested_for for this.

Nice work overall though!

Please mark reply as Helpful/Correct, if applicable. Thanks!


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!

View solution in original post

2 REPLIES 2

Allen Andreas
Administrator
Administrator

Hi,

This line can be adjusted as:

gr.addQuery('user',current.variables.requested_for);

and remaining script like:

gr.query();
if (gr.next()) {
gr.deleteRecord();
}

This is assuming your sys_id for the group is correct and there is a variable called requested_for for this.

Nice work overall though!

Please mark reply as Helpful/Correct, if applicable. Thanks!


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!

That did it for me! Thank you so much!