How to create 'for loop' in workflow as Flow Designer

AnilM99
Tera Expert

Hi Team,

I created a PowerShell activity in the workflow and created a list collector variable.

My requirement is

We have to add multiple users to the AD group, but in the AD group, only one user can be added at once.

So, we should use a 'for loop' to run PowerShell activity multiple times.

 

Please help me on the same.

Thanks,

Anil!

 

5 REPLIES 5

J Siva
Tera Sage

Hi @AnilM99 
Are you using a custom PowerShell script to fulfill this requirement? If so, you can add multiple users at once using the following cmdlets.

# Define the group name
$groupName = "YourADGroupName"

# List of users to add
$users = @("user1", "user2", "user3")

# Add each user to the group
Add-ADGroupMember -Identity $groupName -Members $users

OR

Add-ADGroupMember -Identity GROUPNAME -Members USERS_IDS
Sample:
Add-ADGroupMember -Identity SvcAccPSOGroup -Members SQL01, SQL02

 Regards,
Siva

Ankur Bawiskar
Tera Patron
Tera Patron

@AnilM99 

how are you running powershell activity in workflow?

You can iterate all the users, something like this in workflow run script

var users = current.variables.listCollectorVariableName.toString().split(',');

for (var i in user) {
    // your powershell script here
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Hi @Ankur

I created a custom PowerShell activity.

 

I want to run this activity in a for loop. 

 

Richard Montoux
Tera Contributor

Hello @AnilM99,

 

I suggest retrieving the users from a List Collector using a Run Script activity in the workflow, like this:

var users = workflow.inputs.user_list; // Replace with the actual list collector variable name
var userArray = users.split(',');

 

The list collector usually returns a comma-separated string of sys_ids, like id1,id2,id3,...

 

In Flow Designer, you can use the For Each action to iterate over the list of users retrieved from the List Collector and call a PowerShell action (Custom Action Script) on each iteration to add one user at a time.

 

You can also create a subflow that handles the user addition to the AD group, and call it from your main workflow using a loop like this:

 

for (var i = 0; i < userArray.length; i++) {
var userId = userArray[i];
var subFlow = new Workflow();
subFlow.startFlow('add_user_to_adgroup', current, {
user_id: userId,
group_id: workflow.inputs.group_id
});
}

 

In the subflow, the PowerShell activity would contain a command like:

 

Add-ADGroupMember -Identity "$group_id" -Members "$user_id"

Regards,