views:

121

answers:

1

Hi all,

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

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

Rytmis
You are correct, I was doing my tests and forget to Change the names. Sorry.But still not works :(
Are you sure? my version looks like this now: function Run-As-Background-Job { begin { $appendToFile = { [System.DateTime]::Now | Out-File c:\users\lauri\test.txt -Append } } process { Start-Job -ScriptBlock $appendToFile } }and that produces "test.txt" with the appropriate content, so maybe there's something else wrong in your code.
Rytmis
I am copying your code :). tried new session and reload my IDE...not works :(
Try this: first type `$job = Run-As-Background-Job`, then wait for a while and type `Receive-Job $job` and see what it outputs. [Edit] An even better way: `Run-As-Background-Job | Wait-Job | Receive-Job`.
Rytmis
Show this error : The term 'PipelineBreakpointerE4078E3092DF4dd9A469F3DC0CBB505C' is not recognized as the name of a cmdlet, function, script file, or o perable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. + CategoryInfo : ObjectNotFound: (PipelineBreakpo...469F3DC0CBB505C:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundExceptionTrying whith Run-As-Background-Job | Wait-Job | Receive-Job
The same error my friend
Works, had to put c:\Testes\teste.txt in quotes "c:\Testes\teste.txt "Thanks for you help . I will continue with my tests :)
Disk fillup speed should be modest with repeated invocations of Out-File; Writing a 100 MiB file already takes ages from PowerShell so that won't do anything bad in quite some time.
Joey
I also made the mistaken assumption that the interval would be milliseconds instead of seconds. :-)
Rytmis

related questions