Start-Job cmdlet - parsing scriptblock parameter

by Jim at 2013-04-19 10:42:06

Why doesn’t this code snippet work?

$cmd = ‘get-process’
Start-Job -ScriptBlock {$cmd}

The scriptblock parameter does not expand the variable $cmd. What am I missing? Obviously, I am looking to dynamically build the contents of $cmd at runtime. Otherwise I would just put the literal command within the scriptblock braces.

by mjolinor at 2013-04-19 10:46:43
Try it this way:

$cmd = [scriptblock]::create('get-process')
Start-Job -ScriptBlock $cmd
by ArtB0514 at 2013-04-19 10:57:05
Since there are numerous ways to accomplish the same task in PowerShell, here’s another:
$cmd = {Get-Process}
Start-Job -ScriptBlock $cmd
by mjolinor at 2013-04-19 11:09:09
The major difference is that the [scriptblock]::create() method will let you build a script block using an expandable string, and include local variables that will be expanded when the scriptblock is created.
by Jim at 2013-04-19 13:28:26
Thanks for help!! Good information from both of you. I do like the [scriptblock]::create() technique for the reasons already mentioned.