Best Way to Dynamically Create a Group when it Doesn't Exist

Brizky
Giga Expert

Hey, folks,

 

I'm in the process of learning ServiceNow while also developing for it.  I have a task that I can't seem to figure out how to approach.

 

I want to go through my collection of users, check their department (if specified) and add them to a group with the same name as that department.  But I also want to check to see if said department exists first.  And if not, create it before adding the user as a member of it.

Being a novice I thought I'd be able to do it via a Workflow.  Got to a certain point and felt that that wasn't the way to do it.  Then I started looking into scripting, which then led me to GlideRecord and after reading through that and trying to figure out where to create the script, I felt that that wasn't the right spot either.

So I'm not sure in what direction I should be heading to do this.  And I'm not experienced enough to know if these approaches are even viable or not.

So just looking for some input that can put me in the right direction.

Thanks,

B.

1 ACCEPTED SOLUTION

You can run it in the Scripts - Background module. As provided, it will only show what it will do.  Once you are comfortable with that, set 'dryRun' to false and run.  Save the output for a record of what was done.  And there will be a "Rollback" option to reverse the changes if desired.

 

Also, if this is a policy you want, then the logic inside the while loop can be used in a Business rule for the sys_user table, so that new records in sys_user will be processed like the script does.  But then when adding a new Department, you can also then create a Group to match, and then when adding a new user, you can manually assign the user to that group.  If a user changes Departments, then you will want to remove the old Group membership and add a new one.

 

I'll be happy to answer any questions.

View solution in original post

5 REPLIES 5

Yeah, this was a great piece to get my feet wet with ServiceNow scripting.  And it's bee years since I've messed around with Javascript; so good on that front too.  I had to add a few more things that I Iearned as I was trying to learn your code:  Using the setWorkflow() function and having ServiceNow return no rows for invalid queries.  And added a few metrics for logging purposes.  But it worked like a charm!  Thanks again, Kilo!