How do I Start a job of a function i just defined?

后端 未结 7 831
臣服心动
臣服心动 2020-11-27 23:34

How do I Start a job of a function i just defined?

function FOO { write-host \"HEY\" } Start-Job -ScriptBlock { FOO } |
Receive-Job

Receive-Job: The term \'         


        
7条回答
  •  盖世英雄少女心
    2020-11-28 00:04

    An improvement to @Rynant's answer:

    You can define the function as normal in the main body of your script:

    Function FOO 
    { 
      Write-Host "HEY" 
    } 
    

    and then recycle this definition within a scriptblock:

    $export_functions = [scriptblock]::Create(@"
      Function Foo { $function:FOO }
    "@)
    

    (makes more sense if you have a substantial function body) and then pass them to Start-Job as above:

    Start-Job -ScriptBlock {FOO} -InitializationScript $export_functions| Wait-Job | Receive-Job
    

    I like this way, as it is easier to debug jobs by running them locally under the debugger.

提交回复
热议问题