【问题标题】:Why does PowerShell parse `$true -or $false` as `CommandElement`s?为什么 PowerShell 将 `$true -or $false` 解析为 `CommandElement`s?
【发布时间】:2013-04-08 07:17:44
【问题描述】:

在 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 运营商:和 左:(真) 正确:(错误) 错误位置:-和 静态类型:System.Boolean 范围:(真)-和(假) 家长:(真)-和(假)

正如预期的那样,AST 将其视为二进制表达式。但是,如果删除括号,它将被解析为命令。

> $true - 或 $false 真的 > $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 : 裸字 值:真 静态类型:System.String 程度:真 父级:真或假 参数名称:或 争论 : 错误位置:-或 范围:-或 父级:真或假 StringConstantType : 裸字 值:假 静态类型:System.String 范围:错误 父级:真或假

我研究了官方 PowerShell 语言规范中的语言语法,但我没有看到它 - 为什么这是一个命令,而不是一个表达式?

【问题讨论】:

    标签: parsing powershell


    【解决方案1】:

    我猜您不希望 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
    

    【讨论】:

    • 没问题。我对字符串插值有这种爱/恨的关系。主要是喜欢它,但它时不时地扩展一些东西,你只是不这么想。 :-)
    猜你喜欢
    • 2022-01-10
    • 2021-07-02
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 2015-03-22
    • 2021-08-08
    • 2013-09-18
    • 2015-03-15
    相关资源
    最近更新 更多