Analyzing Script Blocks

by Jul 17, 2013

Script blocks are simply pieces of PowerShell code. You probably use them all the time in scripts and functions. A script block is defined by braces and could be as simple as this:

$a = { Get-ChildItem C:\ } 

Now, the variable $a holds code that can be handed over to function parameters (where appropriate) or be executed when you need it:

$a.Invoke() 

In PowerShell 3.0, you can do a lot more. You can, for example, analyze the script block content. This line will return all the tokens and logical sections identified by the PowerShell parser and abstract syntax tree (AST):

$a.AST.FindAll({$true},$true)

Twitter This Tip! ReTweet this Tip!