- Post History
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
on 09-14-2018 12:31 PM
UPDATED 8/2/2020
I have provided 2 update sets on the service-now share site for your convenience as well and instructions and screenshots.
NEW ARTICLE:
https://community.servicenow.com/community?id=community_article&sys_id=f53ffa4fdb92581411762183ca961...
SERVICE-NOW SHARE:
https://developer.servicenow.com/connect.do#!/share/contents/7409105_test?t=PRODUCT_DETAILS
BELOW HAS BEEN EDITED AND OLD CODE REMOVED!!!
Hey Folks,
I'm back at it and trying to solve problems that i have encountered and i've seen on the community that many of you have experienced as well...
In OOB Orchestration for Active Directory, there is an activity to Add User to Group. And it works great. It does exactly what it's supposed to do. And it has it's uses. However, there is a serious need for the ability to add to multiple groups. Or the ability to add multiple user to a single group, or sometimes, even multiple users to multiple groups.
Wouldn't it be nice if you needed to add 10 users to 10 groups each, you could do that in one single activity, instead of 100 separate activities?
Stay tuned and keep reading for the ability.
Now for the Standard OOB Add User to Group.
1. It works well, but not quite good enough for what everyone wants.
2. If the user is already in the group, it will return a failure from the activity.
I understand that this is an activity, so if the user is already in the group, it will not perform an action and technically fails, but this is not ideal for holding up a workflow. If a user is already in the group, i'd like it if the workflow would continue without me having to look through it to see the user is already in the group. I know, i could write an if script to look for a "user already in group" failure code. But lets simplify this some. If a user is already in a group, and you try to add, then Success in my book, not action needed, but not a failure. It means i verified they were already in the group.
3. If you need to add a user to 15 groups, you either need to run 15 different workflows, or find a way for the add user to group to cycle back around via another script.
I would like to be able to send an array of groups and be done with it. I dont care if a user is already in the group or not. If a user is already in the group, great, move on to the next group.... Also, i would like to know which ones were added and which ones they were already a member of.
So i'm a ServiceNow Developer/Admin/Engineer or whatever else you want to call me. My expertise is not on the Active Directory side. and in turn is not on the Powershell side. So i was beating my head against a wall facing these issues.
Now my resolution was to create a new Activity.
FULL DISCLAIMER HERE:
My Setup for testing.....
This was all done and tested on Kingston, since London is having Mid Server issues right now when i tried this exact same thing on London, nothing would process through the ECC queue.
1. I have a VM running server 2008, acting as a DNS Server, DHCP Server and a AD Domain server. (self contained domain)
2. I have a VM running Windows 7 pro running as the machine holding my Mid Server service. (on the above domain)
3. My personal Developer site is straight OOB Kingston, only alterations/customization were done to create these activities and test them.
NONE OF THIS WAS DONE IN A CORPORATE ENVIRONMENT, SO MAKE SURE YOU TEST EVERYTHING THOROUGHLY BEFORE MOVING TO PRODUCTION.
CHECK WITH YOUR ACTIVE DIRECTORY TEAM TO MAKE SURE THESE ACTIONS ARE OK WITH THEM.
Since there are a lot of people, including myself, that seem to think the Docs for ServiceNow are not always the best at giving examples, those of you who are more technical, please forgive me, but i'm going to go through this for those developers/admins that are new to servicenow and go through this step by step. As this particular subject seems to be a very sore spot for a lot people, i want to make sure it's very clear on how to create this and how it's used.
- 11,245 Views
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Ahhhhh thank you Steven!! Haven't tried it yet, but sounds like exactly what I'm looking for! I was surprised to see that this wasn't OOTB w/ AD Orchestration.

- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Steven, this is awesome! I am trying this now in Jakara but can't get two things to work.
1. I am not seeing the logging happening in the results
2. I cannot get the custom actions when I do Test Inputs to work. It appears to work but does not add the users to the groups. The normal OOB Add User to Group - v1 and Remove User from Group -v1 work great.
Any ideas?
Thanks!
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
What version of SN are you running.
i have in the last few days run some more tests. I am not able to get this working in Jakarta, but it does work in Kingston and London.
keep in mind, i'm running on a brand new OOB instance during these tests.
I'm wondering if it's the JRE version that makes this possible to cycle through the users/groups.

- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
I am running Jakarta so that may be the case.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Steven,
Nice work with the scripts and new activity. That could be very useful to a lot of people.
I had a similiar need and accomplished it with a sub workflow off of our primary main Access Request workflow.
Essentially I pass the User ID and AD groups the user needs to be added to (and the apps just for notifying the AD Team and commenting on the RITM) in workflow inputs and then loop through each group to add the user. It will create a manual task for the AD Team if the Orchestration error is anything besides "The object already exists". It will then comment on the RITM what was done and send an email to the AD Team to let them know what was completed:
Email to Active Directory Team:
RITM Comments:
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi Steven,
Can you post the script that you have used to handle the error in the if loop.
I am able to retrieve the errorMsg from wf_log, but not able to handle it.
What I am trying to achieve here is, if the errorMSG contains " object already exists" , move to the next group to add them for the user, if not notify support team.
The tricky part here I came across is the errorMsg is something like this The object already exists. (Exception from HRESULT: 0x0000000000)Stack Trace:, so not able to handle this by using ; if(errormsg ==' object already exists") , do we have contains or has function we can use here.
Any help on this will be appreciated.
Thank you,
Parimala. S. L
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hey Parimala,
Here is the run script where I add the error to a scratchpad variable (Above the IF statement in the below screenshot):
var addtogroupoutput = data.get(3).errorMessage;
workflow.scratchpad.addtogrouperror = addtogroupoutput;
Here is the IF script I use to handle the error:
answer = ifScript();
function ifScript() {
if (workflow.scratchpad.addtogrouperror.indexOf("The object already exists") > -1) {
return 'no';
}
return 'yes';
}
Basically that IF script says "If object already exists shows up in the error, then no I do not need a manual task". indexOf is the "contains" like function of ServiceNow.
You just need to change "workflow.scratchpad.addtogrouperror" to your "errorMsg". I stored the error in a scratchpad variable (I did this in the Run Script above the IF) so I could use it in this IF statement:
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi ,
I am working on an orchestration project for Onboarding. Everything is working fine as expected till yesterday.
We had a patch upgrade to Kingston patch 9 yesterday and after that I am receiving the below error when executing Create AD object.
Any help on this is really appreciated, as we have a go-live date next weekend and I haven't seen any clue on the community with this error.
the failure output isFailed to Create User's Active Directory Account RITM's sys_id = ""Workflow Context sys_id = "" A device attached to the system is not functioning.Stack Trace: at System.DirectoryServices.DirectoryEntry.CommitChanges()at CommitChanges(Object , Object[] )at System.Management.Automation.DotNetAdapter.AuxiliaryMethodInvoke(Object target, Object[] arguments, MethodInformation methodInformation, Object[] originalArguments) 11-14-2018 08:48:20
Thank you.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi Steven,
Can you help me with the authentication issues when I add ad groups.
I am able to add them successfully without any issues until the patch upgrade happened.
Now we are on Kingston patch 9 and MY account seems like lost some permissions. I am able to add " DL's" using activity add users to groups but not able to add other Groups which are not DL (Distribution lists).
Receiving Authentication failure with the local MID server service credential error.
We have a go live date on next weekend.
Any help or suggestion would be greatly appreciated.
Thank you.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
We are on Kingston Patch 9 as well, but we don't have any issues. Most of the AD Groups we are adding to have a group type of Security (not Distribution).
My suggestion would be take the account you are using for Orchestration and go to AD and attempt to manually (if possible) try to add users to groups using that account. Basically make sure that account can access everything it needs to be able to access (the server, the fields, etc..) You could also run Test Credential in ServiceNow to your AD Server, but you've probably already done that.
From our perspective, we wanted this AD Orchestration account to have as little permissions as possible in order to complete it's work. So the account we use only has this permission:
- Delegate the following rights in Active Directory for the ServiceNowOrch group:
- Group Properties
- Read Members
- Write Members
- Group Properties
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
EDIT: I was able to create a group-add/remove loop to solve my issue and I have attached it to this comment. One day I'll come back to this post and figure out how to make it add all groups in one go. Maybe when we start going over our transaction limit...
Hey Steven!
I really appreciate all of the effort that you put into this! I am on the London release and I ran into an issue that you may or may not be able to help with.
So my goal is to create a group "subscription" catalog item where a user can go to the catalog item in the Service Portal and subscribe or unsubscribe to groups by selecting a checkbox. Then it compares the checkboxes to their existing AD groups through Ajax and creates an array of groups to add and an array of groups to remove. I've put those variables in the scratchpad so I'm set with the username and list of groups.
This makes your project perfect for me because I can use the "ADAddSingleUserToMultipleGroups" script to add the user to those arrays. However, when I tried going through your steps I got stuck on Testing Inputs for the "Add Single User to Multiple Groups" workflow activity. I have attached a screenshot of what it returns when I submit a test input. If I use just one group it does the same thing, however, it works correctly when I test the inputs of the original "Add User to Group" workflow activity.
I have made the following changes to my instance so far:
- Made sure the Mid Server Properties mirrored yours in the video (powershell, etc)
- Created the ADAddSingleUserToMultipleGroups Script File
- Created the ADCustomAddUserstoGroups.psm1 file based off of the ActiveDirectory.psm1 file
- Created the "Add Single User to Multiple Groups" workflow activity based off of the "Add User to Group" workflow activity
- Added the output field
- Added the post processing script
My credentials are working since I was able to add the user to a group with the original workflow activity, but I was wondering if maybe there was something I was missing. I have the user and groups in different folders besides the default Groups and Users folders, but I feel like that shouldn't matter because it's searching for the DN and it works for the original activity.
Either way, I appreciate the help already. If I can't get this to work then I'll figure out a way to loop through the group activity multiple times.
- Drew
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Apologize for not responding earlier....This is the script where I evaluate if a manual task is needed or not. Return NO if it's not needed.
answer = ifScript();
function ifScript() {
if (workflow.scratchpad.addtogrouperror.indexOf("The object already exists") > -1) {
return 'no';
}
return 'yes';
}
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Steven,
I am on London Patch 6 and trying 3. ADAddMultipleUsersToMultipleGroups. It doesnt add 2 users to same group. My output is below. Can you please tell me what is going wrong?
{
"hresult": null,
"output": "\n",
"errorMessages": null,
"debugMessages": "2019-04-23 06:12:52 Executing command: C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -executionpolicy unrestricted -noninteractive -nologo -noprofile -command \"& {& 'scripts\\PowerShell\\PSScript.ps1' -computer '172.20.10.86' -user 'corporate\\SVC_SNowAutomation' -password '******' -script 'C:\\Bunzl Development\\agent\\scripts\\PowerShell\\AD\\ADAddMultipleUsersToSingleGroup.psm1' 'use_mid_service_account' $false -useCred $true -ismid $false -isDiscovery $false -debug $true -logInfo $true -skipTest $false; exit $LASTEXITCODE}\"\r\n2019-04-23 06:12:52 Credential: corporate\\SVC_SNowAutomation\r\n2019-04-23 06:12:52 PowerShell Version: 5.1.14393.2879\r\n2019-04-23 06:12:53 Env vars:\t$env:SNC_credType:AD\t$env:SNC_groupname:_TestDistributionGroup1\t$env:SNC_username:DWillman,KGayson\n\r\n2019-04-23 06:12:53 Executing PSScript.ps1 172.20.10.86 C:\\Bunzl Development\\agent\\scripts\\PowerShell\\AD\\ADAddMultipleUsersToSingleGroup.psm1 True False False\r\n2019-04-23 06:12:53 Running testCredentialAD with user corporate\\SVC_SNowAutomation\r\n2019-04-23 06:12:53 \tCredential created for AD\r\n2019-04-23 06:12:53 \tVars:\t$computer : 172.20.10.86\t$debug : True\t$isDiscovery : False\t$isMid : False\t$script : C:\\Bunzl Development\\agent\\scripts\\PowerShell\\AD\\ADAddMultipleUsersToSingleGroup.psm1\t$skipTest : False\t$useCred : True\n\r\n\r\n",
"credentialDebugInfo": "2019-04-23 06:12:52 Tried Credential: name=Orchestration Windows Credentials, affinity: yes, status=success, sysid=9aefa53413387700a994d3228144b03f, username=corporate\\SVC_SNowAutomation, type=Windows, order=100\r\n",
"eccSysId": "353dd328138d73407a6135528144b07c",
"tags": {
"__text__": "\n"
}
}
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Drew,
Did you find a solution for this problem? I am having the same issue on London, Patch 6.
Thanks
Sangita
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Unfortunately I did not. The workflow/solution above worked for my needs, but it is costly in terms of transactions if you are using it for multiple users to multiple groups.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Thanks. Do you know any other solution where I could add "Multiple Users" to Single Group?
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
This is what I get when I tried Steven's code.
{
"hresult": null,
"output": "\n",
"errorMessages": null,
"debugMessages": "2019-04-23 06:12:52 Executing command: C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -executionpolicy unrestricted -noninteractive -nologo -noprofile -command \"& {& 'scripts\\PowerShell\\PSScript.ps1' -computer '172.20.10.86' -user 'corporate\\SVC_SNowAutomation' -password '******' -script 'C:\\Bunzl Development\\agent\\scripts\\PowerShell\\AD\\ADAddMultipleUsersToSingleGroup.psm1' 'use_mid_service_account' $false -useCred $true -ismid $false -isDiscovery $false -debug $true -logInfo $true -skipTest $false; exit $LASTEXITCODE}\"\r\n2019-04-23 06:12:52 Credential: corporate\\SVC_SNowAutomation\r\n2019-04-23 06:12:52 PowerShell Version: 5.1.14393.2879\r\n2019-04-23 06:12:53 Env vars:\t$env:SNC_credType:AD\t$env:SNC_groupname:_TestDistributionGroup1\t$env:SNC_username:DWillman,KGayson\n\r\n2019-04-23 06:12:53 Executing PSScript.ps1 172.20.10.86 C:\\Bunzl Development\\agent\\scripts\\PowerShell\\AD\\ADAddMultipleUsersToSingleGroup.psm1 True False False\r\n2019-04-23 06:12:53 Running testCredentialAD with user corporate\\SVC_SNowAutomation\r\n2019-04-23 06:12:53 \tCredential created for AD\r\n2019-04-23 06:12:53 \tVars:\t$computer : 172.20.10.86\t$debug : True\t$isDiscovery : False\t$isMid : False\t$script : C:\\Bunzl Development\\agent\\scripts\\PowerShell\\AD\\ADAddMultipleUsersToSingleGroup.psm1\t$skipTest : False\t$useCred : True\n\r\n\r\n",
"credentialDebugInfo": "2019-04-23 06:12:52 Tried Credential: name=Orchestration Windows Credentials, affinity: yes, status=success, sysid=9aefa53413387700a994d3228144b03f, username=corporate\\SVC_SNowAutomation, type=Windows, order=100\r\n",
"eccSysId": "353dd328138d73407a6135528144b07c",
"tags": {
"__text__": "\n"
}
}
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
This is what I got when I tried Steven's code.
{
"hresult": null,
"output": "\n",
"errorMessages": null,
"debugMessages": "2019-04-23 06:12:52 Executing command: C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -executionpolicy unrestricted -noninteractive -nologo -noprofile -command \"& {& 'scripts\\PowerShell\\PSScript.ps1' -computer '172.20.10.86' -user 'corporate\\SVC_SNowAutomation' -password '******' -script 'C:\\Bunzl Development\\agent\\scripts\\PowerShell\\AD\\ADAddMultipleUsersToSingleGroup.psm1' 'use_mid_service_account' $false -useCred $true -ismid $false -isDiscovery $false -debug $true -logInfo $true -skipTest $false; exit $LASTEXITCODE}\"\r\n2019-04-23 06:12:52 Credential: corporate\\SVC_SNowAutomation\r\n2019-04-23 06:12:52 PowerShell Version: 5.1.14393.2879\r\n2019-04-23 06:12:53 Env vars:\t$env:SNC_credType:AD\t$env:SNC_groupname:_TestDistributionGroup1\t$env:SNC_username:DWillman,KGayson\n\r\n2019-04-23 06:12:53 Executing PSScript.ps1 172.20.10.86 C:\\Bunzl Development\\agent\\scripts\\PowerShell\\AD\\ADAddMultipleUsersToSingleGroup.psm1 True False False\r\n2019-04-23 06:12:53 Running testCredentialAD with user corporate\\SVC_SNowAutomation\r\n2019-04-23 06:12:53 \tCredential created for AD\r\n2019-04-23 06:12:53 \tVars:\t$computer : 172.20.10.86\t$debug : True\t$isDiscovery : False\t$isMid : False\t$script : C:\\Bunzl Development\\agent\\scripts\\PowerShell\\AD\\ADAddMultipleUsersToSingleGroup.psm1\t$skipTest : False\t$useCred : True\n\r\n\r\n",
"credentialDebugInfo": "2019-04-23 06:12:52 Tried Credential: name=Orchestration Windows Credentials, affinity: yes, status=success, sysid=9aefa53413387700a994d3228144b03f, username=corporate\\SVC_SNowAutomation, type=Windows, order=100\r\n",
"eccSysId": "353dd328138d73407a6135528144b07c",
"tags": {
"__text__": "\n"
}
}
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Can i take input as LIST Collector? will it work?
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
I was able to use the scripts to add single user to multiple groups. However after adding to user to groups if I run the activity again I do not get anything in the out but in the error. Below screen shot for reference. Can anyone help me with this issue.
I have just used scripts 1,4,5.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
And while using the scripts 1,2,3 please add the extension .ps1 to make them work.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
How would I be able to pull information from Service Portal variables using this. I haven't been able to figure this out yet
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
I have noticed this doesn't work with Multi Row variable sets, Any idea on how to get this working. Its like it doesn't see group names under the variable, I even tried selecting one group thinking it was taking the variable as one long string but that even fails.
thoughts?
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi all! This is great. However, I'm getting an error on the "add single user to multiple groups": (&(objectClass=Group)(samaccountname=["AD_GROUPNAME")) could not be found
HRESULT: [-2147024809]
Stack Trace:
Also - is the business rule needed?
Can anyone assist?
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi Kim,
I had this exact same problem, My problem turned out to be the white space after my variable, a simple click of the space bar after pasting my AD name in was the cause. removed the spaces and now it works,
I am not using the business rule in my case, I am however using numbers 1,4 & 5 along with some other ideas ive found on orchestration to have an automated workflow started from our Service Portal
hope this helps
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hey Dan...
Thanks for the tip -- I checked, no trailing spaces. Any other tips?
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
All -- I just got this to work. I had to convert my array to a string.
while(gr.next()){
modArray.push(gr.u_groups.getDisplayValue());
workflow.scratchpad.gname = modArray.toString();


- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Thanks for the post. At least for me, I'm able to use the AD Update Activity in the Orchestration pack in a workflow however, my issue was even though I had only two fields from my catalog item being used to update the respective users AD account (just as a test)...it would work if everything was a single word. Like I did first name and title. So I tried Johnny and then Developer. That worked no issue.
However...if I tried Johnny and then title of SQL Dev ...it would fail. After a few more attempts I basically just narrowed it down to anything with a space in it...it was going to fail. So then I saw in your post where you just went ahead and created your own object to use. I did the same and with setting the object myself using " "s etc and not relying on ${current.variables.title} in the makeshift object data I had within the activity, it worked.
So it's definitely a bit clunky, but once you get the hang of it, you should be fine.
Thanks!
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
The AD activities to add user to groups uses the sAMAccountName values for the groups and users. spaces are not allowed in those fields.. there are some other limitations, like i believe 20 characters or less, no special characters.
this may help: https://social.technet.microsoft.com/wiki/contents/articles/11216.active-directory-requirements-for-...


- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi,
Yea. I wasn't talking about adding anyone to group and mentioned specifically the AD Update Activity and the title specifically as well. Either way, thanks
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
When i run this i get
Wrapped ReferenceError: "activityOutput" is not defined. |
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi Steven,
Need one quick information. Can we set domain controller port 636 instead 389 for AD activity add user to group. There is no field when configuring activity in the workflow. is there any other way to do so? Due to security reasons we can't open 389 port, which is default port.
Thanks in advance.

- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi Steven,
Is there a way to Check if the user is member of AD group even before using "Add user to a Group" activity. Something that I can achieve "Query AD".
Here is what I'm trying to achieve. I need to check if the user belongs to Group A before adding them in Group B and if the user is in Group A then I have to remove him from Group A and Add then to Group B.
Thanks.

- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Thank you Steven! Hard to believe SN doesn't provide something like this OOB.
Is anyone using this successfully in New York version? I'm not getting any output variables when I test the activity. I have powershell debug on but it isn't showing any errors, just not giving me the output. I am only using scripts 1, 4 and 5 to add a single user to multiple groups.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Sorry for the long Delay, i haven't been on the community much recently as i have been extremely busy.
Well, yes this would be possible.
This would be a multiple step process. or you could create a custom activity.
You can query AD for the user, and you can get back the "member of" attributes. You can then write a Workflow script to look for a certain group to get your answer. then you would have to use the AD Remove from group event, then the AD Add to Group event.
So yes, you can definitely do this.
otherwise, if you want to do a lot of powershell scripting, you can create a custom activity with custom powershell where you can pass 2 groups, the one to check on, and the one to add.
If you want to do it this way, then you can do everything in custom powershell activity and not have to go back and forth with ServiceNow and Powershell.
Something to think about when making a choice here.
1. Is this Repeatable? if not is it worth making it.
2. Which one is easier on the system?
3. Which one has the least amount of Developer "debt"?
So you can write a 1000 line script that does EVERYTHING. But it's not reusable. It's a 1 time use script. I doubt you'll ever be able to use that exact script anywhere else in any system.
But you could write smaller chunks of code where they can be reused.
This is what ServiceNow has done with their AD activities, a single use item. "Add user to Group" it has one very specific purpose and can be reused.
Now, with what you are wanting to do, theoretically yes it's possible, but if this is going to be run dozens or hundreds of times a day, could be very system demanding.
Ultimately, you want the one that will be the easiest to create, that wont have to be watched daily.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
🙂 sure thing, I haven't been on the community much recently.
I actually just setup all of my VM's again yesterday because i wanted to do some checks on New York and on Orlando. So hang tight and hopefully i'll have time to post some updates for New York and Orlando
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
as of right now i'm not sure we have the ability to change the port. I have not completely looked at all the scripts. There may be a way to customize the script to use that port, but i have never had the need to look into this.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Thank you Steven,
This is a Great post!! I had the same issue in New York where it was not working at all, there was no ouput, error message or result so, I tried to debug the issue until I came up with a solution (at least it worked for me). Just rename the MID Server Script files with the extension so:
- ADCustomAddUserstoGroups is renamed to ADCustomAddUserstoGroups.psm1
- ADAddMultipleUsersToMultipleGroups is renamed to ADAddMultipleUsersToMultipleGroups.ps1
- ADAddMultipleUsersToSingleGroup is renamed to ADAddMultipleUsersToSingleGroup.ps1
- ADAddSingleUserToMultipleGroups is renamed to ADAddSingleUserToMultipleGroups.ps1
When it was not working for me, I copied the original code of AddUserToADGroup.ps1 into ADAddSingleUserToMultipleGroups, which in theory should have made it work but it still was not working, so I thought it was not finding the script file which lead me to add the extension to files (looking at the pattern on script names).
Hope this helps!!
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
UPDATED 8/2/2020
I have provided 2 update sets on the service-now share site for your convenience as well and instructions and screenshots.
NEW ARTICLE:
https://community.servicenow.com/community?id=community_article&sys_id=f53ffa4fdb92581411762183ca961...
SERVICE-NOW SHARE:
https://developer.servicenow.com/connect.do#!/share/contents/7409105_test?t=PRODUCT_DETAILS
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Thank you Steven! Thanks for the post. I'm able to implement this successfully.
But here there is no failure message configured if the group provided is invalid/not exist. currently I am working in 'Remove users from groups'. Coppied here the script from mid server script file-CUSTOMActiveDirectory.psm1...Could you please help how to modify this- to display a failure message if group is not existing in AD.
<#########################################################
# CUSTOM - Remove AD user account from Group
#########################################################>
function CUSTOMremoveADUsersAccountFromGroups {
param([string]$domainController, [string]$username, [string]$groupname, [boolean]$useCred, [System.Management.Automation.PSCredential]$credential)
SNCLog-ParameterInfo @("Running CUSTOMremoveADUsersAccountFromGroups ", $domainController, $username, $groupname)
$userObject = getADObject -domainController $domainController -type "User" -objectName $username -useCred $useCred -credential $credential
$groupObject = getADObject -domainController $domainController -type "Group" -objectName $groupname -useCred $useCred -credential $credential
$groupIdentity = $groupObject.Properties["member"].Value
$userIdentity = $userObject.Properties["distinguishedName"].Value
If ($groupIdentity -contains $userIdentity ){
$groupObject.remove("LDAP://"+$userObject.distinguishedName);
if (-not $?) {
SNCLog-DebugInfo "`tFailed to remove user: '$username' account to group: $groupname, $error"
return $result = "`tFailed to remove user: '$username' account to group: $groupname, $error"
}
else{
SNCLog-DebugInfo "`tSUCCESS: user: '$username' Removed From group: '$groupname'"
return $result = "`tSUCCESS: user: '$username' Removed From group: '$groupname'"
}
}
else{
SNCLog-DebugInfo "`tSKIPPED: user: '$username' Is NOT a member of group: '$groupname'"
return $result = "`tSKIPPED: user: '$username' Is NOT a member of group: '$groupname'"
}
}
<#######################################################################
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hey Saranya,
currently the way it is, is that if the script cannot find an AD object, it stops and returns an error.
we can add some "error" handling into the script and not make it return an error and stop, but continue through all users/groups.
<############################################
# CUSTOM - Add AD user account to Group
############################################>
function CUSTOMaddADUsersToGroups {
param([string]$domainController, [string]$username, [string]$groupname, [boolean]$useCred, [System.Management.Automation.PSCredential]$credential)
SNCLog-ParameterInfo @("Running CUSTOMaddADUsersToGroups ", $domainController, $username, $groupname)
$userObject = getADObject -domainController $domainController -type "User" -objectName $username -useCred $useCred -credential $credential
$groupObject = getADObject -domainController $domainController -type "Group" -objectName $groupname -useCred $useCred -credential $credential
if ($userObject -eq $null) {
SNCLog-DebugInfo "`tERROR: Could not find user: '$username', $error"
return $result = "`tERROR: Could not find user: '$username', $error"
}
if ($groupObject -eq $null) {
SNCLog-DebugInfo "`tERROR: Could not find group: '$groupname', $error"
return $result = "`tERROR: Could not find group: '$groupname', $error"
}
$groupIdentity = $groupObject.Properties["member"].Value
$userIdentity = $userObject.Properties["distinguishedName"].Value
If ($groupIdentity -notcontains $userIdentity ) {
$groupObject.add("LDAP://" + $userObject.distinguishedName);
if (-not $?) {
SNCLog-DebugInfo "`tERROR: Failed to add user: '$username' account to group: $groupname, $error"
return $result = "`tERROR: Failed to add user: '$username' account to group: $groupname, $error"
}
else {
SNCLog-DebugInfo "`tSUCCESS: user: '$username' Added to group: '$groupname'"
return $result = "`tSUCCESS: user: '$username' Added to group: '$groupname'"
}
}
else {
SNCLog-DebugInfo "`tSKIPPED: user: '$username' Already a member of group: '$groupname'"
return $result = "`tSKIPPED: user: '$username' Already a member of group: '$groupname'"
}
}
<#########################################################
# CUSTOM - Remove AD user account from Group
#########################################################>
function CUSTOMremoveADUsersAccountFromGroups {
param([string]$domainController, [string]$username, [string]$groupname, [boolean]$useCred, [System.Management.Automation.PSCredential]$credential)
SNCLog-ParameterInfo @("Running CUSTOMremoveADUsersAccountFromGroups ", $domainController, $username, $groupname)
$userObject = getADObject -domainController $domainController -type "User" -objectName $username -useCred $useCred -credential $credential
$groupObject = getADObject -domainController $domainController -type "Group" -objectName $groupname -useCred $useCred -credential $credential
if ($userObject -eq $null) {
SNCLog-DebugInfo "`tERROR: Could not find user: '$username', $error"
return $result = "`tERROR: Could not find user: '$username', $error"
}
if ($groupObject -eq $null) {
SNCLog-DebugInfo "`tERROR: Could not find group: '$groupname', $error"
return $result = "`tERROR: Could not find group: '$groupname', $error"
}
$groupIdentity = $groupObject.Properties["member"].Value
$userIdentity = $userObject.Properties["distinguishedName"].Value
If ($groupIdentity -contains $userIdentity ) {
$groupObject.remove("LDAP://" + $userObject.distinguishedName);
if (-not $?) {
SNCLog-DebugInfo "`tERROR: Failed to remove user: '$username' account to group: $groupname, $error"
return $result = "`tERROR: Failed to remove user: '$username' account to group: $groupname, $error"
}
else {
SNCLog-DebugInfo "`tSUCCESS: user: '$username' Removed From group: '$groupname'"
return $result = "`tSUCCESS: user: '$username' Removed From group: '$groupname'"
}
}
else {
SNCLog-DebugInfo "`tSKIPPED: user: '$username' Is NOT a member of group: '$groupname'"
return $result = "`tSKIPPED: user: '$username' Is NOT a member of group: '$groupname'"
}
}
and now to make this work as is, we have to edit one more thing. I'll post the whole function here, but it's in the getADObject, we have to comment out a line that returns the errors and causes it to stop.
it is this:
<######################
# Fetch an existing AD object by name
#
######################>
function getADObject {
param([string]$domainController, [string]$type, [string]$objectName, [boolean]$useCred, [System.Management.Automation.PSCredential]$credential)
SNCLog-ParameterInfo @("Running getADObject", $domainController, $type, $objectName)
$rootEntry = getDirectoryEntryObject -path "LDAP://$domainController" -useCred $useCred -credential $credential
$search = New-Object System.DirectoryServices.DirectorySearcher $rootEntry;
$sAMAccountName = getSAMAccountName -name $objectName -type $type
SNCLog-DebugInfo "`t`$sAMAccountName:$sAMAccountName"
$search.Filter = "(&(objectClass=$type)(samaccountname=$sAMAccountName))";
$result = $search.FindOne();
if ($result -eq $null) {
SNCLog-DebugInfo "`tUnable to find the AD object"
<### throw New-Object System.ArgumentException($search.Filter + " could not be found"); ###>
return $null;
}
$object = $result.GetDirectoryEntry();
if ($object -eq $null) {
SNCLog-DebugInfo "`tUnable to retrieve the object from AD"
throw New-Object System.ArgumentException("The object could not be retrieved from: " + $search.Filter);
}
return $object;
}
this is what it used to do:

- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hey
Thank you for your solution; it works great in our Production environment for over a year!
Meanwhile, recently we started having a rare issue: when WF activity fails with
SEVERE *** ERROR *** The object already exists.
although the user was a member of the group, we are trying to add him to. And it should have been filtered by the condition:
If ($groupIdentity -notcontains $userIdentity)
I did some digging, and it turns out that AD has a limit on maximum number of objects it can return. This limit is set to 1500. And if the group has more than 1500 members, AD returns only 1500 group members and ignores the rest. Here is a useful link to understand it in more detail.
What approach would you recommend to fix that?
Thank you!

- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
Hi @Steven Young ,
I am getting below error while adding user to group, Also I am using Microsoft active directory V2 Spoke
"Server instance not found on the given port."
can you please suggest what could be the issue here.