Static analysis is the process of evaluating code without executing it. Static analysis in PowerShell makes use of an Abstract Syntax Tree (AST): a tree-like representation of a block of code.
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...