Skip to content

Commit 734f159

Browse files
sdwheelerDCtheGeek
authored andcommitted
Fixes #4648 - ternary operator (#4800)
* Fixes #4648 - ternary operator * fix line wrap
1 parent d5cf9b1 commit 734f159

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

reference/7/Microsoft.PowerShell.Core/About/about_If.md

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ else {
8181
To further refine this example, you can use the Elseif statement to display
8282
a message when the value of $a is equal to 2. As the next example shows:
8383

84-
8584
```powershell
8685
if ($a -gt 2) {
8786
Write-Host "The value $a is greater than 2."
@@ -95,6 +94,31 @@ else {
9594
}
9695
```
9796

97+
### Using the ternary operator syntax
98+
99+
PowerShell 7.0 introduced a new syntax using the ternary operator. It follows the C# ternary
100+
operator syntax:
101+
102+
```Syntax
103+
<condition> ? <if-true> : <if-false>
104+
```
105+
106+
The ternary operator behaves like the simplified `if-else` statement. The `<condition>` expression
107+
is evaluated and the result is converted to a boolean to determine which branch should be evaluated
108+
next:
109+
110+
- The `<if-true>` expression is executed if the `<condition>` expression is true
111+
- The `<if-false>` expression is executed if the `<condition>` expression is false
112+
113+
For example:
114+
115+
```powershell
116+
$message = (Test-Path $path) ? "Path exists" : "Path not found"
117+
```
118+
119+
In this example, the value of `$message` is "Path exists" when `Test-Path` returns `$true`. When
120+
`Test-Path` returns `$false`, the value of `$message` is "Path not found".
121+
98122
## SEE ALSO
99123

100124
[about_Comparison_Operators](about_Comparison_Operators.md)

reference/7/Microsoft.PowerShell.Core/About/about_Operators.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,13 @@ $($x * 23)
442442
$(Get-WmiObject win32_Directory)
443443
```
444444

445+
#### Ternary operator `? <if-true> : <if-false>`
446+
447+
You can use the ternary operator as a replacement for the `if-else` statement in
448+
simple conditional cases. The ternary operator was introduced in PowerShell 7.0.
449+
450+
For more information, see [about_If](about_If.md).
451+
445452
## See also
446453

447454
[about_Arithmetic_Operators](about_Arithmetic_Operators.md)

0 commit comments

Comments
 (0)