Creating Script Blocks from Strings

by Jul 18, 2013

Sometimes you may want to create a script block dynamically from a string. This could be necessary to include local variable content, for example.

To turn a string into a script block, you cannot cast the string. Instead, use this approach:

$folder = 'c:\windows'
$text = "Get-ChildItem -Path $folder"

$sb = [ScriptBlock]::Create($text)
$sb

$sb.Invoke() 

As you can see, the script block in $sb now contains the literal string found in the local variable $folder, and since the result is really a script block, you can now invoke it or hand it over to other functions.

Twitter This Tip! ReTweet this Tip!