Create Dynamic Script Blocks

by Jun 10, 2015

Script blocks are pieces of executable PowerShell code. You typically create them by enclosing code in braces.

To dynamically create script blocks from inside your script, here is a way how you can turn a string into a script block.

$scriptblock = [ScriptBlock]::Create('notepad'

This way, your code can first create the code as string, then turn the string into a script block, and then submit the script block to whatever cmdlet you want (for example, Invoke-Command):

 
PS> Invoke-Command -ScriptBlock 'notepad'
Cannot convert  the "notepad" value of type "System.String" to type  
"System.Management.Automation.ScriptBlock". (raised by:  Invoke-Command)

PS> Invoke-Command -ScriptBlock ([ScriptBlock]::Create('notepad')) 
 

Twitter This Tip! ReTweet this Tip!