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

心不动则不痛 提交于 2019-11-26 10:01:28

问题


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 \'FOO\' is not recognized as the name of cmdlet,
function ,script file or operable program.

What do I do? Thanks.


回答1:


As @Shay points out, FOO needs to be defined for the job. Another way to do this is to use the -InitializationScript parameter to prepare the session.

For your example:

$functions = {
    function FOO { write-host "HEY" }
}

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

This can be useful if you want to use the same functions for different jobs.




回答2:


@Rynant's suggestion of InitializationScript is great

I thought the purpose of (script) blocks is so that you can pass them around. So depending on how you are doing it, I would say go for:

$FOO = {write-host "HEY"}

Start-Job -ScriptBlock $FOO | wait-job |Receive-Job

Of course you can parameterize script blocks as well:

$foo = {param($bar) write-host $bar}

Start-Job -ScriptBlock $foo -ArgumentList "HEY" | wait-job | receive-job



回答3:


The function needs to be inside the scriptblock:

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



回答4:


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.




回答5:


It works for me.

Start-Job -ScriptBlock ${Function:FOO}


来源:https://stackoverflow.com/questions/7162090/how-do-i-start-a-job-of-a-function-i-just-defined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!