转换VBScript的Imp运算符

时间:2017-06-22 13:28:44

标签: powershell vbscript

如果您使用Google PowerShell Imp,则您目前会在列表顶部找到VBScript-to-Windows PowerShell Conversion Guide。然而答案很大程度上是技术上的帮助:

Imp运营商

定义: 对两个表达式执行逻辑暗示。

我们对Imp运营商了解多少?两件事:1)它在Visual Basic .NET中不受支持,2)我们从未听说过任何人实际使用它。因此,我们要说的是,是否存在与Windows PowerShell等效的内容并不重要。

事实上,我在VBScript中多次使用Imp运算符(也写作:A→B),如果存在,可能会在PowerShell中使用它。

示例1

我想复制任何未隐藏的文件,除非它被设置为存档(也需要复制)。
对此的命令可能是:

If (($File.Attributes -match "Hidden") -imp ($File.Attributes -match "Archive")) {Copy $File}

示例2

我有一个带有Log-Entry别名的Log-Debug cmdlet。与原生Write-Host / Write-Debug功能类似;使用Log-Debug 别名时,不会显示信息,只会在提供公共-Debug时进行记录。 对此的命令可能是:

If (($Noun -eq "Debug") -imp $MyInvocation.BoundParameters.Debug.IsPresent) {Add-content $LogFile $$Entry}

如何使用最少的代码构建逻辑蕴涵运算符?

1 个答案:

答案 0 :(得分:0)

如果你从字面上理解这个定义,那么你可能会发表一个逻辑暗示的陈述:

If ($Expression1) {If ($Expression2) {DoThis}} Else {DoThis}

由于您需要执行两次相同的功能,因此可能会过度安静。 因此,最好使用单个If条件替换VBScript的Imp运算符,这使我想出了:

If (($True, [Bool]$Expression2)[[Bool]$Expression1]) {...}

但是进一步的调查让我甚至更简单地替换了VBScript的Imp运营商:

If (!$Expression1 -or $Expression2) {...}

检查

0..3 | ForEach {
    $Expression1, $Expression2 = [Int]($_ / 2), [Int]($_ % 2)
    New-Object PSObject -Property @{
        Expression1 = [Bool]$Expression1
        Expression2 = [Bool]$Expression2
        Implication = !$Expression1 -or $Expression2
    }
} | Format-Table -AutoSize

真值表

Expression1 Expression2 Implication
----------- ----------- -----------
      False       False        True
      False        True        True
       True       False       False
       True        True        True

注意:在此解决方案中,$Null表达式被视为$False。这与VBScript Imp实现不同,但与包含$Null表达式的其他PowerShell运算符一致。例如VBScript语句:If 1 And vbNull Then msgbox "True" Else msgbox "False",返回True,其中PowerShell语句If (1 -And $Null) {"True"} Else {"False"}返回False

按位

如果您正在寻找一个按位Imp运算符(可能应该调用它 - bImp,如果存在的话),那么它将是:

$Implication = -bNot Expression1 -bOr Expression2    # e.g.: -bNot 3 -bOr 5 = -3 (-bAnd 0xF = 13)