Start-Job cmdlet - parsing scriptblock parameter

This topic contains 0 replies, has 1 voice, and was last updated by Profile photo of Forums Archives Forums Archives 5 years, 5 months ago.

  • Author
    Posts
  • #5825

    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.

    Thanks,
    Jim

    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.

You must be logged in to reply to this topic.