Parsing PowerShell script with AST Parsing PowerShell script with AST powershell powershell

Parsing PowerShell script with AST


Using PS3.0+ Language namespace AST parser:

$text = Get-Content 'pester-script.ps1' -Raw # text is a multiline string, not an array!$tokens = $null$errors = $null[Management.Automation.Language.Parser]::ParseInput($text, [ref]$tokens, [ref]$errors).    FindAll([Func[Management.Automation.Language.Ast,bool]]{        param ($ast)        $ast.CommandElements -and        $ast.CommandElements[0].Value -eq 'describe'    }, $true) |    ForEach {        $CE = $_.CommandElements        $secondString = ($CE | Where { $_.StaticType.name -eq 'string' })[1]        $tagIdx = $CE.IndexOf(($CE | Where ParameterName -eq 'Tag')) + 1        $tags = if ($tagIdx -and $tagIdx -lt $CE.Count) {            $CE[$tagIdx].Extent        }        New-Object PSCustomObject -Property @{            Name = $secondString            Tags = $tags        }    }
Name       Tags             ----       ----             'Section1' @('tag1', 'tag2')'Section2' 'foo', 'bar'     'Section3' 'asdf'           'Section4' 

The code doesn't interpret the tags as a list of strings, but simply uses the original text extent.
Use the debugger in PowerShell ISE / Visual Studio / VSCode to inspect the various data type cases.