일. 8월 17th, 2025

Power Automate Cloud, a core component of Microsoft Power Platform, empowers users to automate repetitive tasks and integrate services without writing complex code. While simple flows can handle basic automation, the true power of Power Automate shines when you leverage conditional statements (조건문) and loops (반복문). These control structures are fundamental building blocks for creating intelligent, robust, and adaptive automation solutions.

In this comprehensive guide, we’ll dive deep into using conditionals and loops, and then explore how to combine them with other advanced features to build truly sophisticated and reliable Power Automate flows. Let’s get started! 🚀


1. Understanding Conditional Statements (조건문) – Making Decisions in Your Flow 🧐

Think of conditional statements as your flow’s decision-making brain. They allow your automation to follow different paths based on whether specific criteria are met. This is crucial for handling various scenarios and ensuring your flow reacts appropriately to different inputs.

What are they?

At their core, conditionals execute one set of actions if a condition is true, and a different set if it’s false. This is often referred to as “If/Else” logic.

Why are they important?

  • Dynamic Workflows: Your flow can adapt to different data or situations.
  • Error Prevention: Handle specific edge cases gracefully.
  • Efficiency: Avoid unnecessary actions by directing the flow down the correct path.

How to use them in Power Automate:

a) The “Condition” Action (If/Else) ✅❌

This is the most common conditional action. It evaluates a single condition and provides two branches: “If yes” (true) and “If no” (false).

Example 1: Approving Requests Based on Amount Let’s say you have a flow that triggers when a new item is created in a SharePoint list for expense reports.

  • Scenario: If the expense amount is less than $1000, it’s automatically approved. If it’s $1000 or more, it requires managerial approval.

    1. Trigger: When an item is created (SharePoint).
    2. Add Action: Search for “Condition” and select it.
    3. Configure Condition:
      • Choose Amount (from dynamic content of the SharePoint item).
      • Select is less than or equal to.
      • Enter 1000.
    4. “If yes” branch (Amount $1000):
      • Start an approval (Approvals) – Assign to a manager.
      • Condition (nested): If approval outcome is “Approved”, update item status to “Approved” and notify. Else (rejected), update status to “Rejected” and notify.

Example 2: Processing Emails with Specific Subjects

  • Scenario: You want to process emails differently based on whether their subject contains “Urgent” or “Report”.

    1. Trigger: When a new email arrives (V3) (Outlook).
    2. Add Action: “Condition”.
    3. Configure Condition:
      • Choose Subject (from dynamic content).
      • Select contains.
      • Enter Urgent.
    4. “If yes” branch (Subject contains ‘Urgent’):
      • Post a message (V3) (Teams) to “Urgent Alerts” channel.
    5. “If no” branch:
      • Add another “Condition” (nested):
        • Choose Subject.
        • Select contains.
        • Enter Report.
      • Nested “If yes” branch (Subject contains ‘Report’):
        • Create file (OneDrive for Business) – Save attachment to a “Reports” folder.
      • Nested “If no” branch (Subject contains neither):
        • Mark as read (Outlook) – Just mark the email as read.
b) The “Switch” Action (Multiple Choice) 🚦

When you have many possible outcomes based on a single value, the “Switch” action is much cleaner than multiple nested “Condition” actions.

Example: Task Assignment Based on Priority

  • Scenario: Tasks arriving in a Planner plan need to be assigned to different teams based on their priority (High, Medium, Low).

    1. Trigger: When a task is created (Planner).
    2. Add Action: Search for “Switch” and select it.
    3. Configure Switch:
      • Choose Priority (from dynamic content of the Planner task).
    4. Add Cases:
      • Case 1: Enter High
        • Assign task (Planner) to “High Priority Team”.
        • Send an email to high-priority escalation contact.
      • Case 2: Enter Medium
        • Assign task (Planner) to “Regular Team”.
      • Case 3: Enter Low
        • Assign task (Planner) to “Backlog Team”.
      • Default (optional): If Priority doesn’t match any of the above, define actions here (e.g., send an error notification).

2. Harnessing the Power of Loops (반복문) – Processing Collections of Data 🔄

Loops allow your flow to perform the same set of actions repeatedly for each item in a collection. This is incredibly powerful for processing lists, files, emails, or any array of data.

What are they?

A loop iterates through an array or list of items, executing the same actions for each item until all items have been processed.

Why are they important?

  • Batch Processing: Handle multiple items efficiently (e.g., all attachments in an email, all rows in an Excel table).
  • Data Transformation: Apply the same logic to many pieces of data.
  • Scalability: Automate tasks that involve varying numbers of items.

How to use them in Power Automate:

a) The “Apply to each” Action ➡️➡️➡️

This is the workhorse of looping in Power Automate. It takes an array as input and executes the actions within its block for every item in that array.

Example 1: Processing All Attachments from an Email

  • Scenario: When an email arrives with attachments, save each attachment to a specific SharePoint folder.

    1. Trigger: When a new email arrives (V3) (Outlook).
    2. Add Action: Search for “Apply to each”.
    3. Configure Apply to each:
      • In the “Select an output from previous steps” field, select Attachments (from dynamic content of the email).
    4. Inside the loop (for each attachment):
      • Create file (SharePoint)
        • Site Address: Your SharePoint site.
        • Folder Path: /Shared Documents/Email Attachments/
        • File Name: Name (from dynamic content of the loop’s Current item)
        • File Content: ContentBytes (from dynamic content of the loop’s Current item)

Example 2: Updating Multiple SharePoint List Items

  • Scenario: After an event, you want to update the status of all attendees from “Registered” to “Attended” in a SharePoint list.

    1. Trigger: Manually trigger a flow (or When an item is modified on an event status list).
    2. Add Action: Get items (SharePoint).
      • Site Address: Your SharePoint site.
      • List Name: Your attendee list.
      • Filter Query (optional): Status eq 'Registered' (to only get registered attendees).
    3. Add Action: “Apply to each”.
    4. Configure Apply to each:
      • Select value (the array of items returned by Get items).
    5. Inside the loop (for each item):
      • Update item (SharePoint)
        • Site Address: Your SharePoint site.
        • List Name: Your attendee list.
        • Id: ID (from dynamic content of the loop’s Current item).
        • Status: Set to “Attended”.

Example 3: Sending Personalized Emails from an Excel Table

  • Scenario: You have a list of customers in an Excel table (Name, Email, Product) and want to send a personalized update to each.

    1. Trigger: Manually trigger a flow.
    2. Add Action: List rows present in a table (Excel Online (Business)).
      • Location, Document Library, File, Table Name: Select your Excel file and table.
    3. Add Action: “Apply to each”.
    4. Configure Apply to each:
      • Select value (the array of rows returned by List rows present in a table).
    5. Inside the loop (for each row):
      • Send an email (V2) (Outlook)
        • To: Email (from dynamic content of the loop’s Current item).
        • Subject: Hello Name , your Product update! (using dynamic content).
        • Body: “Dear Name, we have an exciting update for your Product…”
b) The “Do until” Action (Less common for collections, more for conditions) 🎯

While “Apply to each” is for iterating over a known collection, “Do until” repeats actions until a condition is met. It’s more about status checking or retries.

  • Example: Repeatedly check a file upload status until it’s ‘Completed’.

3. Building Advanced Flows (고급 흐름 만들기) – Combining Power Automate Features 🛠️

True automation prowess comes from orchestrating these control structures with other advanced features. This allows for complex business processes, robust error handling, and scalable solutions.

Key Advanced Concepts:

a) Variables 📦

Variables are temporary storage containers for data within your flow. They are essential for manipulating data, counting iterations, building dynamic strings, and passing information between steps.

  • Initialize variable: Define the variable’s name, type (String, Integer, Boolean, Array, Object), and initial value.
  • Set variable: Change the variable’s value.
  • Increment variable: Increase an Integer variable by a specific amount.
  • Append to array variable: Add an item to an array.
  • Append to string variable: Add text to a string.

Example: Counting processed items within a loop.

  • Inside an Apply to each loop (e.g., processing invoices), Increment variable (an Integer variable named ProcessedInvoicesCount) after each successful processing. After the loop, Send an email summarizing “X invoices processed”.
b) Expressions 🧠

Expressions are powerful functions that allow you to manipulate data dynamically. They are used in actions where you need to perform calculations, format dates, extract text, or build complex conditions.

  • Common Functions:
    • formatDateTime(utcNow(), 'yyyy-MM-dd'): Format current date.
    • length(outputs('Get_items')?['body/value']): Get the number of items returned.
    • contains(triggerBody()?['Subject'], 'Invoice'): Check if a string contains another string.
    • addDays(utcNow(), 7, 'yyyy-MM-dd'): Add days to a date.
    • int('123'): Convert a string to an integer.

Example: Dynamically naming files or filtering data.

  • When saving an attachment, you might use concat(formatDateTime(utcNow(), 'yyyyMMdd_HHmmss'), '_', triggerOutputs()['headers']['x-ms-file-name']) to ensure a unique file name.
  • In a condition, you might use empty(outputs('Get_items')?['body/value']) to check if a list of items is empty.
c) Scopes 🔗

A “Scope” action acts as a container for other actions. It’s incredibly useful for organizing your flow, especially for advanced error handling. You can configure how the scope should run (e.g., “Run after” a previous step fails), effectively creating “Try-Catch” blocks.

Example: “Try-Catch” Block for a critical process.

  1. Scope 1: “Try Process”
    • Contains all your main actions (e.g., calling an API, creating a record).
  2. Scope 2: “Handle Success”
    • Configure run after for this scope to run only is successful of “Try Process”.
    • Actions: Send success notification, update status.
  3. Scope 3: “Handle Failure”
    • Configure run after for this scope to run only has failed or has timed out of “Try Process”.
    • Actions: Send error notification to admin, log error details.
d) Parallel Branches ⚙️

Sometimes, you want to perform multiple, independent actions simultaneously. “Add a parallel branch” allows your flow to split and execute actions concurrently, which can improve performance.

Example: Notifying multiple stakeholders.

  • After an approval is completed, you might want to:
    1. Send an email to the requester.
    2. Post a message in a Teams channel for the project team.
    3. Update a status in a separate tracking system. These three actions can run in parallel.
e) Error Handling (Configure Run After) 🚨

This is critical for building robust flows. Every action has “Configure run after” settings, which determine when it should run relative to the previous action’s outcome (is successful, has failed, is skipped, has timed out).

Example: Sending an error notification.

  • After an action that might fail (e.g., Create file on a full disk):
    1. Add a Send an email action.
    2. Click the “…” on the email action, select “Configure run after”.
    3. Deselect “is successful” and select “has failed” for the previous Create file action. Now, the email will only be sent if the file creation fails.
f) Child Flows (Callable Flows) 💡

For reusable logic, you can create a “child flow” (also known as a callable flow). This flow can be triggered by another flow, allowing you to centralize common processes like an approval workflow or a data validation routine.

Example: Reusable Approval Process.

  • Create a child flow that takes an “Item ID” and “Approver Email” as inputs, handles the approval logic, and returns “Approval Status” as an output.
  • Now, any parent flow (from a SharePoint trigger, email trigger, etc.) can simply call this child flow whenever an approval is needed, reducing redundancy and making maintenance easier.
g) HTTP Requests 🌐

For advanced integrations with services that don’t have direct connectors, or to interact with custom APIs, the “HTTP” action is invaluable. You can send GET, POST, PUT, DELETE requests and process the JSON responses.

Example: Integrating with a custom OCR API.

  • Inside a loop processing image files:
    1. HTTP action: POST request to your custom OCR API endpoint.
      • Body: Include the image file content from the current loop item.
    2. Parse JSON action: Parse the response from the OCR API to extract the text.
    3. Condition: If OCR text is extracted successfully, proceed to update a database.

Comprehensive Example: Automating Invoice Processing 🧾

Let’s combine everything we’ve learned into a powerful, real-world scenario:

Goal: Automate the processing of incoming invoices via email.

  1. Trigger: When a new email arrives (V3) (Outlook)

    • Has Attachments: Yes
    • Include Attachments: Yes
  2. Initialize Variables:

    • ProcessedInvoicesCount (Integer) = 0
    • FailedInvoicesList (Array) = []
  3. Condition 1: Check Email Subject and Attachment Type

    • Subject contains Invoice AND Attachments is not null.
    • If yes: (Proceed to process)
    • If no: (Ignore email or send a polite reply)
      • Mark as read (Outlook)
  4. Apply to each: For each Attachment (from Attachments of the email)

    • Condition 2: Check File Extension (nested)
      • Name (of current attachment) ends with .pdf OR Name ends with .jpg
      • If yes:
        1. Scope: “Try OCR Extraction”
          • HTTP action: Call an AI Builder (or custom) OCR model.
            • Method: POST
            • URI: Your AI Builder/OCR endpoint.
            • Headers: Content-Type: application/json
            • Body: Construct JSON with ContentBytes of the attachment.
          • Parse JSON: Parse the OCR response to extract invoice data (Vendor, Amount, Date).
          • Condition 3: If OCR Extraction Successful (check if required fields are present)
            • If yes:
              1. Create item (SharePoint) in “Invoice Tracking” list using extracted data.
              2. Start an approval (Approvals) for the invoice.
              3. Condition 4: If Approval Outcome is Approved
                • Update item (SharePoint) – Set status to “Approved”.
                • Send an email to vendor (using data from variables and dynamic content).
                • Increment variable: ProcessedInvoicesCount.
                • If no (Rejected):
                • Update item (SharePoint) – Set status to “Rejected”.
                • Send an email to internal finance team.
            • If no (OCR failed to extract data):
              • Append to array variable: FailedInvoicesList (add attachment name and reason).
              • Send an email to admin: “OCR failed for attachment Name“.
        2. Configure run after for a nested Scope “Handle OCR Failure”:
          • This scope runs if “Try OCR Extraction” has failed or has timed out.
          • Append to array variable: FailedInvoicesList (add attachment name and “System Error”).
          • Send an email to IT support: “Critical error during OCR for attachment Name.”
      • If no (Unsupported file type):
        • Append to array variable: FailedInvoicesList (add attachment name and “Unsupported File Type”).
        • Send an email to sender: “Unsupported file type attached: Name.”
  5. After the “Apply to each” loop:

    • Scope: “Summary Report” (Configure to run is successful after the loop)
      • Send an email (V2) to finance manager:
        • Subject: Invoice Processing Summary - formatDateTime(utcNow(), 'yyyy-MM-dd')
        • Body: “Total invoices processed: ProcessedInvoicesCount.”
        • Body: “Failed invoices: string(variables('FailedInvoicesList')).” (Convert array to string for email)

Best Practices & Tips for Robust Flows ✨

  • Naming Conventions: Give meaningful names to all actions and variables (e.g., Condition - Is Amount High?, Apply to each - Process Attachments, varProcessedCount).
  • Add Comments: For complex logic, add comments to actions. This significantly improves readability and maintainability.
  • Thorough Testing: Test all possible paths in your conditions and loops, including edge cases (e.g., empty lists, zero amount, wrong file type).
  • Modular Design (Child Flows): Break down large flows into smaller, reusable child flows.
  • Comprehensive Error Handling: Always assume things can go wrong. Use Configure run after and Scopes to catch errors and notify appropriate people.
  • Performance Considerations:
    • Minimize the number of Get items or List rows actions inside loops if possible. Fetch all data once and then filter it.
    • Be mindful of API call limits for connectors.
  • Security: Use dedicated service accounts for flows that interact with sensitive data or systems.
  • Solutions: Package your flows, environment variables, and connections into Power Apps Solutions for better ALM (Application Lifecycle Management), including version control and deployment.

Conclusion 🌟

Power Automate Cloud’s conditional statements and loops are indispensable tools for moving beyond simple, linear automation. By mastering the “Condition,” “Switch,” and “Apply to each” actions, and by integrating advanced features like variables, expressions, scopes, and error handling, you can build sophisticated, intelligent, and resilient automation solutions.

Start small, experiment with these concepts, and gradually build up to more complex scenarios. The ability to make decisions and process collections of data will unlock countless possibilities for streamlining your workflows and transforming how you get work done. Happy automating! 🚀💡 G

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다