about_If
簡短描述
描述可用來根據一或多個條件式測試結果來執行語句清單的語言命令。
完整描述
如果指定的條件測試評估為 true,您可以使用 if
語句來執行程式碼區塊。 如果所有先前的測試都評估為 false,您也可以指定一或多個額外的條件測試來執行。 最後,如果沒有其他條件式測試評估為 true,您可以指定執行的其他程式碼區塊。
Syntax
下列範例顯示 if
語句語法:
if (<test1>)
{<statement list 1>}
[elseif (<test2>)
{<statement list 2>}]
[else
{<statement list 3>}]
當您執行 if
語句時,PowerShell 會將 <test1>
條件表達式評估為 true 或 false。 如果 <test1>
為 true, <statement list 1>
則執行 ,且 PowerShell 會 if
結束 語句。 如果 <test1>
為 false,PowerShell 會評估條件語句所 <test2>
指定的條件。
如需布爾值評估的詳細資訊,請參閱 about_Booleans。
如果 <test2>
為 true, <statement list 2>
則執行 ,且 PowerShell 會 if
結束 語句。 如果 和 都<test1>
評估為 false,則程式代碼區塊會><statement list 3
執行,而 PowerShell 會if
結束 <test2>
語句。
您可以使用多個 elseif
語句來鏈結一系列的條件式測試。 只有在所有先前的測試都為 false 時,才會執行每個測試。 如果您需要建立 if
包含許多 elseif
語句的語句,請考慮改用 Switch 語句。
範例:
最簡單的 if
語句包含單一命令,而且不包含任何 elseif
語句或任何 else
語句。 下列範例顯示最簡單的 語句形式 if
:
if ($a -gt 2) {
Write-Host "The value $a is greater than 2."
}
在此範例中 $a
,如果變數大於 2
,條件會評估為 true,且語句清單會執行。 不過,如果 $a
小於或等於 2
或不是現有的變數, if
語句就不會顯示訊息。
藉由新增 Else 語句,當$a小於或等於 2 時,就會顯示訊息。 下一個範例顯示:
if ($a -gt 2) {
Write-Host "The value $a is greater than 2."
}
else {
Write-Host ("The value $a is less than or equal to 2," +
" is not created or is not initialized.")
}
若要進一步精簡此範例,當的值$a
等於 2
時,您可以使用 elseif
語句來顯示訊息。 下一個範例顯示:
if ($a -gt 2) {
Write-Host "The value $a is greater than 2."
}
elseif ($a -eq 2) {
Write-Host "The value $a is equal to 2."
}
else {
Write-Host ("The value $a is less than 2 or" +
" was not created or initialized.")
}
使用三元運算符語法
PowerShell 7.0 引進了使用三元運算符的新語法。 它會遵循 C# 三元運算符語法:
<condition> ? <if-true> : <if-false>
三元運算符的行為就像簡化 if-else
語句一樣。 系統會 <condition>
評估表達式,並將結果轉換成布爾值,以判斷接下來應該評估哪一個分支:
- 如果
<condition>
運算式為 True,就會執行<if-true>
運算式 - 如果
<condition>
運算式為 False,就會執行<if-false>
運算式
例如:
$message = (Test-Path $path) ? "Path exists" : "Path not found"
在這裡範例中, 值$message
是 Path exists
傳回 時。Test-Path
$true
當傳$false
回 時Test-Path
,的$message
Path not found
值為 。
$service = Get-Service BITS
$service.Status -eq 'Running' ? (Stop-Service $service) : (Start-Service $service)
在此範例中,如果服務正在執行,則會停止,如果其狀態不是 [ 執行中],則會啟動它。
<condition>
如果 、 <if-true>
或 <if-false>
表示式呼叫命令,您必須將它包裝在括弧中。 如果沒有,PowerShell 會在表達式中<condition>
引發 命令的自變數例外狀況,並剖析 和 <if-false>
表達式的<if-true>
例外狀況。
例如,PowerShell 會引發這些三元的例外狀況:
Test-Path .vscode ? Write-Host 'exists' : Write-Host 'not found'
(Test-Path .vscode) ? Write-Host 'exists' : Write-Host 'not found'
(Test-Path .vscode) ? (Write-Host 'exists') : Write-Host 'not found'
Test-Path: A positional parameter cannot be found that accepts argument '?'.
ParserError:
Line |
1 | (Test-Path .vscode) ? Write-Host 'exists' : Write-Host 'not found'
| ~
| You must provide a value expression following the '?' operator.
ParserError:
Line |
1 | (Test-Path .vscode) ? (Write-Host 'exists') : Write-Host 'not found'
| ~
| You must provide a value expression following the ':' operator.
此範例會剖析:
(Test-Path .vscode) ? (Write-Host 'exists') : (Write-Host 'not found')
exists