Introduction to expressions in Power Automate

4 months ago 199
ARTICLE AD

Introduction to expressions

Completed100 XP

2 minutes

When you build a flow in Power Automate, it's easy to get started by adding a trigger and actions and then passing data between them with dynamic content. But, in most cases you need to perform more complex operations. You may want to do a calculation, to transform data for your solution, or access, convert, and compare values. To do these things, you can look to expressions.

In Power Automate, expressions are a set of simple functions that enable you to return data. Put simpler, you use expressions to write a formula to get your data the way you want it. Expressions allow you to do things like convert a date to UTC, divide two numbers, create that perfect string by combining fields, and much more all by using various functions.

Flows in Power Automate run on top of Azure Logic Apps. This is relevant because they both use all of the same functions. When you're searching the internet for solutions or reading documentation about Power Automate functions, it's common to end up looking at Logic Apps documentation. For example, the Reference Guide of functions for Power Automate is hosted on the Logic Apps side of the documentation.

Through the rest of this module, you'll learn about the different types of functions and the syntax so you can start to use expressions in your flows.


Next unit: Get started with expressions

Get started with expressions

Completed100 XP

3 minutes

To write an expression in Power Automate, select a field to open the Dynamic content menu and then select Expression as shown here.

Screenshot of opening the Dynamic content menu and selecting Expression.

The formula box is where you can type your expressions by combining one or more functions. Before you learn about the different types of functions and their usage, there are some commonalities you should learn first. Function names aren't case-sensitive.

 Tip

Notice in the screenshot that we used a Manually triggers a flow trigger and a Compose action. This allows you to have a simple setup for writing and testing your expressions without worrying about other inputs or actions. Use this setup to follow along in this app or any time you want to try out something new.

When you enter a function in the formula bar, you see a pop-up with syntax suggestions.

Screenshot of pop-up with syntax suggestions.

Here you can see for the convertFromUtc function that it has two required inputs and one optional input.

Timestamp is required and expects a string

destinationTimeZone is required and expects a string

format? is optional and expects a string.

 Note

The question mark at the end of format tells you that it is an optional input.

After you enter a Timestamp as a string then typing a comma, the flow prompts for the destinationTimeZone:

Screenshot of prompt for the destinationTimeZone.

This can be daunting. What does it want for the time zone? If you look in the pop-up, you see that it provides a link to the list of time zone values. This page provides you with the string for the destinationTimeZone. With that information, we can now complete the expression.

convertFromUtc('2024-02-09T12:00:00Z','Eastern Standard Time')

Once the expression is completed, you can select OK to save your changes. Always be sure to select OK or UPDATE when editing an expression. If you select out of the inputs, you lose your changes. Power Automate doesn't have AutoSave.

With your first expression complete, you can now select Test in the top right-hand corner. Then select Save & Test.

Once the test is complete, you should see the green bar that says "Your flow ran successfully." Expand the Compose action and you see that the OUTPUTS is your date time converted to the new time zone.

Screenshot of successful flow bar with the message Your flow ran successfully.

Use this same process to see the output of any test expressions you create.


Next unit: Notes make things easier

Notes make things easier

Completed100 XP
2 minutes

When you look at the convertToUtc expression you wrote earlier, you might notice that you need to scroll to see the whole formula in the function bar. A common technique to make reviewing your expression easier is to use notes and paste the whole formula into the note.

Screenshot of pasting the formula into the comment.

To add a note, select the ellipse to show the menu. Then select Add a note.

Screenshot of selecting the ellipsis to reveal the "Add a note" option.

In the note box, you can type any text you want. This can be text or just a copy and paste of the expression used in your action.

Defining text

When you use text in a Power Automate expression, you use the single quote (') at the beginning and end of each string. For example, if you wanted to combine the string "Today is" and the output from our expression above that returns a date in an expression, you would use the Concat function and your syntax would be:

concat('Today is ',outputs('Compose'))

Screenshot of the concat function syntax.

These little details help you become more effective when working with expressions. One of the great things about expressions is that they're consistent. As you learn about one function you can often apply those learnings to the next function, rapidly speeding up your learning.


Next unit: Types of functions

Types of functions

Completed100 XP
12 minutes

Functions are grouped into 10 different categories like math and logic. The categories are organized to make finding a particular function easier. Below you get an overview of each category and some examples.

Keep in mind as you go through the various examples, we use static text and values. This is to allow you to test and recreate the examples as easily as possible. In your flows, you can substitute dynamic content in place of this static data. Just ensure that your dynamic data is the correct format for the function.

In the screenshot below, notice to the right of each category header (like String functions or Collection) the words See more. By selecting See more, the complete list of functions for that category are shown.

Screenshot of the Expression tab with the See more option for a complete list of functions.

Select See more beside String functions.

Screenshot of See more String functions with replace(text, oldText, newText) selected.

String functions

String (text) functions are used to modify strings, find characters in a string, format strings, and more. Text manipulation is a core skill often used when trying to better format or modify data you received from somewhere else.

An example of a string function is the formatNumber function. This function can convert a number into a string in a given format. A common request is to make a number look like currency. To change the number 12.5 into $12.50, use the following formula:

regexCopy
formatNumber(12.5,'C')

The C represents the Currency numeric format string. Don't worry, a list of the other options are available at Standard numeric format strings. You might be asking what if you wanted to show the number as currency but with the Yen symbol? There's an optional parameter where you can pass the locale.

regexCopy
formatNumber(12.5,'C','ja-JP')

This formula returns ¥13.

Collection functions

These functions are used for arrays and strings. They can be used to check if an array is empty, to grab the first, or last item, or even for join, union, and intersection operations.

An example of a helpful Collection function is length. You can use length to return the number of items in a string or array. The following example would be used to count the number of characters in the string "I love Power Automate."

regexCopy
length('I love Power Automate.')

The output would be 22. Notice that a space counts as one character. You can use this type of function for validation or in conjunction with the String functions to manipulate strings.

Logical functions

These functions are used to work with conditions, to compare values, and to do other logic-based evaluations. These are often thought of as If statements where you want to compare if a number is greater than another number. Power Automate supports all of the logical comparisons you would expect.

In the example below, an expression compares if 12 is greater than 10 and then output the appropriate string. This is also your first expression that uses more than one function. We combine if and greater logical functions.

regexCopy
If(greater(12,10),'Yes','No')

The result of this expression would be the string Yes. To understand the expression, work from the inside out. Greater(12,10) returns true or false depending on whether 12 is greater than 10. Since it is, the value returned is true.

Now that you know the answer is true, you can see that the If function returns the data after the first comma. In this case that is the string Yes. Had it been false then the string No would have been returned.

 Important

While you can write logical expressions as shown above, there is also an action called Condition that lets you write If statements without an expression. You can insert a new step in your flow by asking Copilot to Insert a condition or by selecting the plus icon and searching for the connector called Condition.

Screenshot of Choose an action with the Condition control selected.

Here's the same condition written using the action.

Screenshot of a condition written using the action.

 Tip

Notice in the above screenshot that Copilot successfully added a Compose down the true branch, but did not add the Compose 4 action in the false branch. Copilot may not always succeed at what you want, so make sure to verify the actions Copilot added are correct.

You'll find over time that you use a combination of both methods depending on your requirements.

Conversion functions

These functions are used to change the type of your data. This can be a simple thing like converting a text number into an integer, or more complex functions like changing the encoding of a file from base64 to binary. Knowing that these functions are available helps you overcome problems you come across when getting your data shaped correctly.

A common scenario is the need to use int or float to change a text number into an actual number. This is common when importing data into your flow from a data source. The number 12 or 12.4 can be stored as text. To use that number in a logical function or write it to a location that expects a number, you need to convert it. The following example changes the string "12" into the integer 12.

regexCopy
Int('12')

That outputs the integer 12. If it was the string "12.4" then you would need to convert it to a float because of the decimal digits. In that case, you would use

regexCopy
Float('12.4')

Now you could use text number to do the previous example.

regexCopy
If(greater(Int('12'), Float('12.4')),'Yes','No')

This would output the string "No" because 12 isn't greater than 12.4. Combining functions like this is common and is a useful pattern to learn.

Math functions

Math functions do exactly as you would expect. They allow you to add, subtract, multiply, and perform other similar functions. Also, Math functions allow you to find the smallest and largest numbers from a data set or get a random number between a specified interval, among other things. To get a random number from 1 to 10, use the following:

regexCopy
rand(1,10)

One thing to keep in mind is that there's a different function for adding numbers (add) and for subtracting numbers (sub). Many formula languages add negative numbers to produce subtraction, but Power Automate doesn't. To add two numbers together, you use the following:

regexCopy
add(12, 13)

This would return 25. If you wanted to add three numbers, then you would need to add a second function like so:

regexCopy
add(add(12,13),15)

This would return 40. As you saw before, you can find yourself nesting functions to get the results you want.

Date and time functions

These functions are used to return the current date and time, change time zones, find specific info about a date and time, and do other date or time manipulations. If you have date and time values in your data, you need these functions.

One important thing to remember as you explore date and time functions in Power Automate is that they're often based on UTC. Most data sources pass data back and forth with Power Automate in UTC format. Also, if you use the function UTCNow(), that returns the current time in UTC format. If you want to use that to compare to user data that is currently in the Eastern Time Zone, then you need to use the following formula to convert it:

regexCopy
convertFromUtc(utcNow(), 'Eastern Standard Time', 'dd-MM-yyyy hh:mm tt' )

This will output 09-02-2024 11:28 AM. For a complete list of the date time format options, see Custom date and time format strings.

Referencing functions

The referencing functions are used to work with the outputs of your actions and triggers. The nice thing is that most of the time, Power Automate writes these functions for you. When you add dynamic content to your flow, you're using referencing functions without knowing it. If you add dynamic content and then hover on top of that content, you can see this in action.

In the screenshot below, you can see this in action by adding the User name dynamic content from my trigger to the Inputs for Compose.

Screenshot of adding User name dynamic content from trigger.

By hovering over User name with the mouse pointer, you can see

regexCopy
triggerOutputs()?['headers']?['x-ms-user-name-encoded']

Power Automate created the expression using the triggerOutputs for you. It's pulling the x-ms-user-name-encoded property from the Headers property. Most of the time in Power Automate you reference these properties via dynamic content. But it's possible to write your own expressions to recreate this if necessary. Each trigger and action have different formats for how you retrieve their data.

Explore these functions by adding different triggers, actions, data sources, and apply-to-each loops in your flow. Then, use their properties as dynamic data to see more examples. The good news is writing these types of expressions isn't common.

Workflow functions

The workflow functions are used to retrieve information about your flow and are closely related to the referencing functions. One of the functions is called workflow. You can use it as shown below.

regexCopy
workflow().run.id

This returns the ID of the current flow run. You could use this for error reporting or logging if needed. These functions aren't commonly used.

URI parsing functions

These functions are used to dissect a URI that is passed in as a string. You can use these functions to find the host, path, query string, or other portions of the URI. The following example shows you how to use uriQuery to get the query string portion of the given URI.

regexCopy
uriQuery('https://flow.microsoft.com/fakeurl?Test=Yes')

This would return the string "?Test=Yes" which you could then parse with string functions to get the value passed in from the URI.

Manipulation functions

Manipulation functions are used to work with specific objects in your flow. You can do things such as find the first non-blank value, work with properties, or find xpath matches. These functions are used typically in JSON or XML nodes evaluations.

One function you might find handy here is coalesce. This function allows you to find the first non-null value from a specified set of values. You use the function as shown in the following formula:

regexCopy
coalesce(null, 'Power Automate', 'Power Apps')

This formula would return the string Power Automate. Handy when you're passing in multiple values and want to find the first one that isn't null.


Next unit: Write complex expressions

Write complex expressions

Completed100 XP
5 minutes

Complex expressions are when you combine more than one function to get the result you want. In the Math functions and Date Time functions sections, you already saw examples of these expressions. You saw that to add three numbers, you need to combine two add functions like:

regexCopy
add(add(12,13),15)

Which resulted in the output of 40.

Then you saw how you use the utcNow function to get the current date and time and then use convertFromUtc to change it to the Eastern Standard time zone as shown here:

convertFromUtc(utcNow(), 'Eastern Standard Time', 'dd-MM-yyyy hh:mm tt' )

Which resulted in the output of 09-02-2024 11:28 AM.

When you think of complex expressions, it's more than one function in an expression where you use the output of one function as an input of another. There's no special syntax, operators, or considerations.

For a final example of a complex expression, take the scenario of having a couple of inputs as part of your Manually trigger a flow trigger and then using that input in a formula to compute a new time. You can use the example flow that you used to test your expressions or to build a new flow that looks like this one.

Screenshot of Manually trigger a flow with Compose input.

Now select Add an input under Manually trigger a flow and add a Number. Then select Add an input again and add a Date. Your trigger should now look like this:

Screenshot of Manually trigger a flow with Number and Trigger date.

Now, in the Compose step you add an expression to add the number of days from the trigger to the date.

regexCopy
addDays(triggerBody()?['key-button-date'], triggerBody()?['number'])

This expression uses the Date Time function addDays and the Referencing function triggerBody.

 Note

If you find yourself asking "How do I know what goes in for trigger body?" then you are thinking correctly. The secret is you can combine dynamic content into your expressions. To do so, start your expression by typing addDays() and then with your cursor between the (), select Dynamic content. Then you can choose your fields as shown here. This is a great way to reference that content while letting Power Automate do the hard work of writing the formula.

Animated screenshot demonstrating how to add an expression.

If you test your flow and enter the date 2024-02-09 and the number 2, your output is 2024-02-11T00:00:00.0000000, UTC format for February 11, 2024.

Now you can find out what day of the week that is by using another Compose action with the following expression:

regexCopy
dayOfWeek(outputs('Compose'))

This returns the value of 4, which represents Thursday as it counts up from Sunday as 0. Here's a screenshot of the current flow to validate what you built. Note the expressions are placed in the note field.

Screenshot of validate flow built with Manually trigger a flow, Compose, and Compose 2.

Now add another Compose step to check to see if the date they selected is a Thursday. Do this with the following expression in Compose 3.

regexCopy
if(equals(outputs('Compose_1'),4), 'You chose a Thursday', 'You did not choose a Thursday')

For February 9, 2024 this will return the string "You did not choose a Thursday."

This example is a typical build pattern for a complex expression, building piece by piece in separate steps. Now that you have all of the functions necessary worked out, add another Compose step. In Compose 4, write one large expression that does everything in one step. The expression looks like:

regexCopy
if(equals(dayOfWeek(addDays(triggerBody()['date'], triggerBody()['number'])),4), 'You chose a Thursday', 'You did not choose a Thursday' )

The output for February 9, 2024 will be the string "You did not choose a Thursday." Congratulations. You wrote a complex expression by doing small steps and then putting it all together in the end.


Next unit: Exercise - Creating a manual flow and using expressions

Exercise - Creating a manual flow and using expressions

Completed100 XP
6 minutes

Let's say you need to find out how much it would cost to carpet a room based on its square footage. In this exercise, you create a manual flow that uses your input to do those calculations.

Sign into Power Automate.

In the Copilot box, type Create an instant flow with two compose actions. Then select Generate.

Screenshot of select manually trigger a flow.

Copilot automatically generates a flow. Review the flow to make sure it has a Manually trigger a flow trigger and two Compose actions.

Select the Manually trigger a flow trigger. The properties pane expands on the left. Select Add an input.

Choose Number and name it Square Footage.

Select Add an input and choose Number again and name it Cost.

Select the first Compose action.

Select the Inputs box and a blue rectangle with a lightning bolt on top and fx on the bottom appears. Select the fx to bring up the expressions bar.

Select the Function tab and type in mul(. Power Automate knows that you're using the multiply expression and automatically add a ) at the end for you.

With your cursor still between the two parentheses in the expression field, select the Dynamic content tab.

Select Square Footage from the dynamic content.

 Tip

If you don't see Square Footage, select See More next to the action's title in the Dynamic Content box to show more property options.

Next add a comma (,) and choose Cost in the dynamic content.

The complete expression should be:

regexCopy
mul(triggerBody()?['number'],triggerBody()?['number_1'])

Select Add to add the expression into the Compose step.

Screenshot of add the expression into the Compose step.

You know your expression is correct if it's added into the Compose step and looks like:

Screenshot of correct expression in Compose step.

This compose step is now doing the math of calculating the square footage of the area multiplied by the cost per square foot based upon inputs you provide. However, we still need to convert the final result to currency to get the correct answer.

Select the Inputs box for the Compose2 and select the blue fx to open the Functions box.

Type in formatNumber(.

With your cursor in place, select the Dynamic content tab and choose Outputs from the previous Compose step.

Next finish the expression with , 'C2'.

The C formats the number as currency, with the 2 representing how many decimal places. Refer to Standard numeric format strings for more number formats.

The complete expression is:

regexCopy
formatNumber(outputs('Compose1'), 'C2')

Select Add to add this expression in the Compose2 step.

Screenshot of add expression to Compose 2 step.

Now after our flow is triggered, it first multiplies the two numbers, then converts the result into the correct currency format. This gives you a quick way to get the cost associated with carpeting a room.

Your complete flow looks like this:

Screenshot of completed flow with Manually trigger a flow, Compose1, and Compose 2.

In the top-right corner, select the Save button, then select Test.

Choose Manually and then select Test.

Enter the two number inputs, Square Footage and Cost, and then select Run flow at the bottom.

The page reloads and you see green check marks next to each step of your flow.

Selecting each step expands the details showing you the inputs and outputs of each step.

Selecting Compose1 shows the multiplied value of the two numbers you entered, while selecting Compose 2 shows the currency format of that multiplied value.

Let's recap what we did.

Manually trigger a flow - Allows us to press a button to trigger a flow and provide inputs. In this case our two inputs are Square Footage and Cost, which we're using to find out the total price to carpet a room.

Compose - Used to write expressions using the data from elsewhere in the flow. In this case, we first multiplied the two inputs from the trigger. This gave us the correct number, but we still needed to convert it to currency. We then used another compose action to format the multiplied result into currency, giving us the answer to how much it would cost to carpet a room.


Next unit: Check your knowledge

Answer the following questions to see what you learned.

1. 

What is the correct syntax for a string in a Power Automate function?

 

This is my string.

'This is my string.'

Power Automate requires single quotes (') around a text to make it a string.

"This is my string."

makeString(This is my string.)

Power Automate requires single quotes (') around a text to make it a string.

2. 

How would you write a formula to add 3 plus 5 and then divide by 2?

 

div(add(3,5),2)

Power Automate requires the use of an expression phrase like "div" and "add" before being provided numbers to make calculations. Start from the inside (the calculation you want to make first, in this case adding 3 and 5) and then work your way out in the formula as you add more calculations (in this case, dividing the sum of 3 and 5 by 2).

(3+5)/2

div(3+5,2)

Power Automate expressions can't be used for math.

3. 

What statement best describes the relationship between Power Automate and Azure Logic Apps functions?

 

You can use the same functions in a Power Automate as you can in Azure Logic Apps.

Each product uses the same functions but has different syntax.

They use the same functions and their function documentation is interchangeable.

You can use the same functions in a Power Automate as you can in Azure Logic Apps.

The two products are similar but you should ignore all function documentation for Azure Logic Apps when building a Power Automate flow.


Next unit: Summary

Read Entire Article