Finding All Variables in a Script Block

To analyze the content of a script block, you can easily examine the AST, and, for example, create a list of all variables in the code:

$code = {

    $a = "Test"
    $b = 12
    Get-Service
    Get-Process
    $berta = 100

}


$code.Ast.FindAll( { $true }, $true) | 
  Where-Object { $_.GetType().Name -eq 'VariableExpressionAst' } |
  Select-Object -Property VariablePath -ExpandProperty Extent |
  Out-GridView

If you’d like to see all commands instead, try this:

$code = {

    $a = "Test"
    $b = 12
    Get-Service
    Get-Process
    $berta = 100

}


$code.Ast.FindAll( { $true }, $true)  | 
  Where-Object { $_.GetType().Name -eq 'CommandAst' } |
  Select-Object -ExpandProperty Extent  |
  Select-Object -Property * -ExcludeProperty *ScriptPosition |
  Out-GridView

This can be useful to create auto-generated documentation for script blocks.

Twitter This Tip! ReTweet this Tip!