使用PowerShell三元運算符簡化條件邏輯

if/then 构造在 PowerShell 代码中很常见,但你知道还有另一种方法叫做三元运算符吗?它可以让你的 if/then 构造更加简洁。让我们学习如何构建一个自定义的 PowerShell 三元运算符。

有人说,用三元运算符来构建条件逻辑更加简洁、简单且代码量更少,但代价是可读性下降。他们说得没错,但在 PowerShell 中拥有类似三元运算符的行为真是太好了!

如果你对三元运算符不熟悉,它基本上是使用哈希表或类似的结构来根据条件做出决策。

在 PowerShell 中的 If/Then

为了解释 PowerShell 三元运算符,让我们先从一个 if/then 构造的例子开始。

$CarColor = 'Blue'
if ($CarColor -eq 'Blue') {
    'The car color is blue'
} else {
    'The car color is not blue'
}

乍一看,你可能觉得没什么问题。实际上,确实没有问题,但是这个条件也可以通过一行代码来测试(在我的个人限制 115 个字符之内)。

现在构建一个 PowerShell 哈希表,其中有两个键;$true$false。然后,将值设为你希望在满足你定义的条件时显示的内容。

@{ $true = 'The car color is blue'; $false = 'The car color is not blue' }
[$CarColor -eq 'Blue']

接下來,定義條件($CarColor 為 Blue),並使用 $CarColor -eq 'Blue' 檢查該條件是否滿足。

$CarColor = 'Blue'
@{ $true = 'The car color is blue'; $false = 'The car color is not blue'}
$CarColor -eq 'Blue'

現在將該條件($CarColor -eq 'Blue')用作散列表中的鍵。這樣做會執行檢查,然後使用結果在散列表中查找鍵。

完成PowerShell三元運算符

$CarColor = 'Blue'
@{ $true = 'The car color is blue'; $false = 'The car color is not blue'}[$CarColor -eq 'Blue']
A custom PowerShell ternary operator

一行代碼!這不是更加簡潔嗎?我們不再使用 if/then 語句,而是使用散列表並根據 $CarColor 是否等於 Blue 進行查找。然後將結果輸出到控制台。如果你想使用這種方法,只需填寫這些空白即可:

@{$true = $ResultyouwanttodoifTrue; $false = $ResultyouwantifFalse}[]

如果需要,你還可以在散列表中包含多個條件並進行檢查,而不僅僅是 $true$false。這是一種簡單的替換長 if/then 語句或 switch 語句的方法。

現在,你已經擁有一個自定義的PowerShell三元運算符,可以立即在你的腳本中使用了!

Source:
https://adamtheautomator.com/powershell-ternary/