user353401
user353401

Reputation: 355

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}      
    }
}

Upvotes: 0

Views: 628

Answers (1)

Rytmis
Rytmis

Reputation: 32037

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. :-)

Upvotes: 1

Related Questions