File tree Expand file tree Collapse file tree 2 files changed +32
-1
lines changed
reference/7/Microsoft.PowerShell.Core/About Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Original file line number Diff line number Diff line change 81
81
To further refine this example, you can use the Elseif statement to display
82
82
a message when the value of $a is equal to 2. As the next example shows:
83
83
84
-
85
84
``` powershell
86
85
if ($a -gt 2) {
87
86
Write-Host "The value $a is greater than 2."
@@ -95,6 +94,31 @@ else {
95
94
}
96
95
```
97
96
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
+
98
122
# # SEE ALSO
99
123
100
124
[about_Comparison_Operators](about_Comparison_Operators.md)
Original file line number Diff line number Diff line change @@ -442,6 +442,13 @@ $($x * 23)
442
442
$(Get-WmiObject win32_Directory)
443
443
```
444
444
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
+
445
452
## See also
446
453
447
454
[ about_Arithmetic_Operators] ( about_Arithmetic_Operators.md )
You can’t perform that action at this time.
0 commit comments