Start-Job cmdlet - parsing scriptblock parameter

Welcome Forums General PowerShell Q&A Start-Job cmdlet - parsing scriptblock parameter

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

  • Author
  • #5825

    Topics: 1562
    Replies: 0
    Points: 0
    Rank: Member

    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.

The topic ‘Start-Job cmdlet - parsing scriptblock parameter’ is closed to new replies.