2013-04-16 26 views
3

在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的官方語言規範的語言語法,我沒有看到它 - 爲什麼這是一個命令,而不是體現在哪裏?

回答

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 
+0

你說得對!我很生氣,我錯過了。謝謝! –

+0

沒問題。我已經有了字符串插值的愛/恨關係。大多數人都喜歡它,但偶爾它會擴展東西,而你不會這麼想。 :-) –

相關問題