Abstract syntax tree

The AST in PowerShell is available for any script block, for example:

{ Write-Host 'content' }.Ast 

The script block that defines a function can be retrieved via Get-Command:

function Write-Content { Write-Host 'content' } 
(Get-Command Write-Content).ScriptBlock 

Or the script block defining a function can be retrieved using Get-Item:

function Write-Content { Write-Host 'content' } 
(Get-Item function:Write-Content).ScriptBlock 

It is possible to work down through the content of the script block using AST. For example, the first argument for the command Write-Host might be accessed:

{ Write-Host 'content' }.Ast. 
                         Endblock. 
                         Statements. 
                         PipelineElements. 
                         CommandElements[1] 

The approach used previously is rough and simply extracts the second command element from the first statement in the end block.

Rather than following the tree so literally, it is possible to execute searches against the tree. For example, the Write-Host command is not necessarily a sensible inclusion; a search for occurrences of the command can be constructed:

{ Write-Host 'content' }.Ast.FindAll( { 
        param ( $ast ) 
 
        $ast -is [Management.Automation.Language.CommandAst] -and  
$ast.GetCommandName() -eq 'Write-Host' 
    }, 
    $true 
) 

In the preceding command, the FindAll method expects two arguments:

  • The first argument is a script block predicate. The predicate is a script block that accepts a single argument, an element from the tree. In the preceding example, a parameter is declared to give the argument a name. The argument is tested by a comparison that will return true or false
  • The second argument is used to decide whether the search should extend to include nested script blocks
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.8.8