如何在Windows PowerShell 4.0中执行短路评估
本文关键字:执行 短路 评估 Windows PowerShell | 更新日期: 2023-09-27 18:29:13
Technet关于Windows PowerShell 4.0的about_Logical_Operators声明如下:
Operator Description Example
-------- ------------------------------ ------------------------
-or Logical or. TRUE when either (1 -eq 1) -or (1 -eq 2)
or both statements are TRUE. True
-xor Logical exclusive or. TRUE (1 -eq 1) -xor (2 -eq 2)
only when one of the statements False
is TRUE and the other is FALSE.
两者似乎都没有进行短路评估。
如何在Windows Powershell 4.0中模拟C#||
或VBOrElse
?
一组简单的测试用例表明短路有效:
PS C:'> 1 -eq 0 -or $(Write-Host 'foo')
foo
False
PS C:'> 1 -eq 1 -or $(Write-Host 'foo')
True
PS C:'> 1 -eq 1 -and $(Write-Host 'foo')
foo
False
PS C:'> 1 -eq 0 -and $(Write-Host 'foo')
False
我一直在寻找同样的答案,却得到了这个答案。在我看来,这是迄今为止最好的。。。
$cueNumber = 512
@{ $true = "This is true"; $false = "This is false" }[$cueNumber -gt 500]
参考:https://adamtheautomator.com/a-simpler-ifthen-conditional-logic-in-powershell/