Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion reference/7/Microsoft.PowerShell.Core/About/about_If.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ else {
To further refine this example, you can use the Elseif statement to display
a message when the value of $a is equal to 2. As the next example shows:


```powershell
if ($a -gt 2) {
Write-Host "The value $a is greater than 2."
Expand All @@ -95,6 +94,31 @@ else {
}
```

### Using the ternary operator syntax

PowerShell 7.0 introduced a new syntax using the ternary operator. It follows the C# ternary
operator syntax:

```Syntax
<condition> ? <if-true> : <if-false>
```

The ternary operator behaves like the simplified `if-else` statement. The `<condition>` expression
is evaluated and the result is converted to a boolean to determine which branch should be evaluated
next:

- The `<if-true>` expression is executed if the `<condition>` expression is true
- The `<if-false>` expression is executed if the `<condition>` expression is false

For example:

```powershell
$message = (Test-Path $path) ? "Path exists" : "Path not found"
```

In this example, the value of `$message` is "Path exists" when `Test-Path` returns `$true`. When
`Test-Path` returns `$false`, the value of `$message` is "Path not found".

## SEE ALSO

[about_Comparison_Operators](about_Comparison_Operators.md)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,13 @@ $($x * 23)
$(Get-WmiObject win32_Directory)
```

#### Ternary operator `? <if-true> : <if-false>`

You can use the ternary operator as a replacement for the `if-else` statement in
simple conditional cases. The ternary operator was introduced in PowerShell 7.0.

For more information, see [about_If](about_If.md).

## See also

[about_Arithmetic_Operators](about_Arithmetic_Operators.md)
Expand Down