在PowerShell中,查看如何解析逻辑运算符的语句:
> $ast = [System.Management.Automation.Language.Parser]::ParseInput( "($true) -and ($false)", [ref]$null, [ref]$null) > $ast.EndBlock.Statements[0].PipelineElements[0].GetType().Name CommandExpressionAst > $ast.EndBlock.Statements[0].PipelineElements[0].Expression Operator : And Left : (True) Right : (False) ErrorPosition : -and StaticType : System.Boolean Extent : (True) -and (False) Parent : (True) -and (False)
正如所料,AST将其视为二进制表达式。但是,如果删除括号,它将作为命令解析。
> $true -or $false True > $ast = [System.Management.Automation.Language.Parser]::ParseInput( "$true -or $false", [ref]$null, [ref]$null) > $ast.EndBlock.Statements[0].PipelineElements[0].Gettype().Name CommandAst > $ast.EndBlock.Statements[0].PipelineElements[0].CommandElements StringConstantType : BareWord Value : True StaticType : System.String Extent : True Parent : True -or False ParameterName : or Argument : ErrorPosition : -or Extent : -or Parent : True -or False StringConstantType : BareWord Value : False StaticType : System.String Extent : False Parent : True -or False
我在官方的PowerShell语言规范中学习了语言语法,我没有看到它 - 为什么这是一个命令,而不是一个表达式?
答案 0 :(得分:2)
我猜你不希望PowerShell在将字符串传递给ParseInput之前对其进行评估。在这种情况下,请使用单引号:
27> $ast = [System.Management.Automation.Language.Parser]::ParseInput( '$true -or $false', [ref]$null, [ref]$null)
28> $ast.EndBlock.Statements[0].PipelineElements[0].Expression
Operator : Or
Left : $true
Right : $false
ErrorPosition : -or
StaticType : System.Boolean
Extent : $true -or $false
Parent : $true -or $false