开发者

Start-Job Problems

Why this code not works ?

function teste 
{
    begin
    {
        function lala {
            while ($true) {
                "JJJJ" | Out-File c:\Testes\teste.txt -Append
            }
        }
    }
    process {
        Start-Job -ScriptBlock {lala}    开发者_StackOverflow  
    }
}


My best guess is scoping. When Start-Job runs your script block, it runs it in a different context -- one where "lala" is not defined. However, if you were to rephrase your code like so:

function Run-As-Background-Job 
{
    begin
    {
        $appendToFile = {
            while ($true) {
                "JJJJ" | Out-File c:\Testes\teste.txt -Append
            }
        }
    }
    process {
        Start-Job -ScriptBlock $appendToFile
    }
}

the background job wouldn't try to invoke a name that isn't defined -- instead, the entire script block would be passed to it and things should work.

Note, that I recommend you test without the while loop like I did, because that's going to fill up your disk rather quickly.

Also, please aim for more meaningful function and variable names when posting code. :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜