Undocumented: Foreach in Copilot Studio
I will cut the chase: there is a way to do for-each loop in Copilot Studio and it is hidden, meaning you cannot find it in its designer UI. This short article will show you how to use it.
Follow below steps:
1. In Copilot Studio, go to your Custom Copilot and open an existing topic or create a new one.
2. Switch to the topic's code editor by click on More on the designer UI's top nav bar and chose "Open code editor".
3. Once you are you are in the code editor, add following lines to the end of the topic's source code:
- kind: Foreach
id: Foreach_Nl2kasnd
4. The alphanumeric string after "Foreach_" is just a random identifier so anything would work.
5. Now Close the code editor and you should see a new action called "Loop through a list" appearing with errors.
6. Don't worry about the errors, we will fix them soon: we need a table variable for the foreach loop and some logic inside the loop.
7. Add an action of "Set a variable value" right before the foreach block and create a new table variable named "table1" and set its value to "[{Name:"option 1"},{Name:"option 2"}]".
领英推荐
8. Go to the "Loop through a list" action we have just created and set "Items to loop over" to table1 and set the "Loop value variable" to "item". It should look like this after the setting.
9. Now we can finally add logics in the loop. let's add a "Send a message" action to the loop and display each record in the table. To do that just make the message to show "item name is: {Topic.item.Name}".
The entire logic should look like this now:
If you test this topic, your topic should return something like below:
The code-behind for all added actions:
actions:
- kind: SetVariable
id: setVariable_AQUI9D
variable: Topic.table1
value: =[{Name:"option 1"},{Name:"option 2"}]
- kind: Foreach
id: Foreach_Nl2kasnd
items: =Topic.table1
value: Topic.item
actions:
- kind: SendActivity
id: sendActivity_ja5k6x
activity: "item name is: {Topic.item.Name}"
Conclusion: Foreach is not yet published but it is fully implemented, well almost: only thing missing is the designer UI component to add it to the design view, but you can add it via the code editor and it is a must for processing table variables.
Happy Veterans Day!
Zewei Song, Ph.D.
Monday, November 11th, 2024
Deliver PowerApps in 4 weeks | SharePoint | Microsoft 365
2 个月Thanks for the tip—great insight!