AST

The AST in PowerShell is available for any script block; an example is as follows:

{ 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 Write-Host command might be accessed, as follows:

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

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

A visual approach
The ShowPSAst module, available in the PowerShell Gallery, may be used to visualize the AST tree. Install the module with: Install-Module ShowPSAst -Scope CurrentUser.

It can be run against a function, a module, a script block, and so on: Show-Ast { Write-Host 'content' }.

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 as follows:

{ Write-Host 'content' }.Ast.FindAll(
{
param ( $ast )

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

In the preceding example, the FindAll method expects two arguments.

The first argument is a script block; a predicate. The predicate accepts a single argument: a node from the tree. A parameter may be declared to give the argument a name; alternatively, the node can be referenced using $args[0]. 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.135.195.249