playing with jobs

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Simeon Iksanov Simeon Iksanov 1 year, 2 months ago.

  • Author
  • #28695
    Profile photo of Simeon Iksanov
    Simeon Iksanov

    I was playing with some little code and found a moment I cannot understand

    $w = '1..10'
    Invoke-Expression $w #this runs OK

    then I try to run it as a job

    start-job {Invoke-Expression $w} # or start-job {Invoke-Expression $global:w}

    this returns an error: Cannot evaluate parameter 'Command' because its argument is specified as a script block and there is no input. A script block cannot be evaluated without input.

    what is wrong?

  • #28700
    Profile photo of Daniel Krebs
    Daniel Krebs

    Hi Simeon,

    You will need to use the $using: scope modifier to let the PowerShell engine know to inject the value of the variable $w into the scriptblock {}.

    $w = '1..10'
    Start-Job { Invoke-Expression $using:w }

    Jobs are running in another process and do not have access to variables in your current session.

    Please consider more then twice if Invoke-Expression is the right command to be included in your scripts. It is a dangerous / harmful command because it allows injection of bad command lines similar to SQL injection and its usage can be avoided in 99.9% of all use cases.


  • #28701
    Profile photo of Richard Siddaway
    Richard Siddaway

    The problem is that that a job runs in a separate Powershell process so in your case $w doesn't exist when Invoke-expression tries to run

    You could do this

    Start-Job -ScriptBlock { $w = '1..10'; Invoke-Expression $w}

    $w = '1..10'
    Start-Job -ScriptBlock { param($w) Invoke-Expression $w} -ArgumentList $w

  • #28702
    Profile photo of Simeon Iksanov
    Simeon Iksanov

    thanks, now I got it

You must be logged in to reply to this topic.