【问题标题】:How to perform short-circuit evaluation in Windows PowerShell 4.0?如何在 Windows PowerShell 4.0 中执行短路评估?
【发布时间】:2014-11-05 20:31:09
【问题描述】:

Technet 的 about_Logical_Operators 关于 Windows PowerShell 4.0 声明如下:

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# ||VB OrElse

【问题讨论】:

  • 您没有读过,是吗 ;) 稍后在文档中您提到:“Windows PowerShell 逻辑运算符仅评估确定语句真值所需的语句...... "
  • @AndrewMorton - 我确实做到了,但我对-or 运算符的描述感到困惑。 Keith Hill's answer 表明它默认会短路并帮助我解决问题。
  • 逻辑上(咳咳,双关语承认),-xor 不可能短路......对吗?它必须评估表达式的两边以确定排他性......对吗?
  • @CodeJockey 听起来不错。

标签: c# vb.net powershell short-circuiting


【解决方案1】:

一组简单的测试用例表明短路是有效的:

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

【讨论】:

【解决方案2】:

我一直在寻找相同的答案,遇到了这个答案。迄今为止我认为最好的...

$cueNumber = 512
@{ $true = "This is true"; $false = "This is false" }[$cueNumber -gt 500]

参考:https://adamtheautomator.com/a-simpler-ifthen-conditional-logic-in-powershell/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-03
    • 2012-08-30
    • 2015-11-14
    • 2017-01-21
    • 2012-02-10
    • 2010-12-21
    • 1970-01-01
    相关资源
    最近更新 更多