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 8181To further refine this example, you can use the Elseif statement to display
8282a message when the value of $a is equal to 2. As the next example shows:
8383
84-
8584``` powershell
8685if ($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)
Original file line number Diff line number Diff 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 )
You can’t perform that action at this time.
0 commit comments