Finding Script Block Variables

by Nov 12, 2015

Script blocks define a PowerShell code without executing it. The easiest way of defining script blocks is placing code into braces.

Script blocks sport a number of advanced features to examine the code they embrace. One is direct access to the abstract syntax tree (AST). The AST can analyze the code. Here is an example that dumps all variable names used inside a script block:

#requires -Version 3

$scriptblock = {

   $test = 1
   $abc = 2


$scriptblock.Ast.FindAll( { $args[0] -is [System.Management.Automation.Language.VariableExpressionAst] }, $true ) |
  Select-Object -ExpandProperty VariablePath | Select-Object -ExpandProperty UserPath

Twitter This Tip! ReTweet this Tip!