Samselvaprabu
Samselvaprabu

Reputation: 18147

How to solve the error while invoking function through Start-Job?

I am having a file named "build.ps1" where there is a function called "Execute-build" available.

I am calling that function from another file named "Dailybuild.ps1" like below.

. ./Build.ps1

# starting different jobs (parallel processing)
$job1 = Start-Job { Execute-Build "List.txt" }
$job2 = Start-Job { Execute-Build "List2.txt" }


# synchronizing all jobs, waiting for all to be done
Wait-Job $job1, $job2

# receiving all results
Receive-Job $job1, $job2

# cleanup
Remove-Job $job1, $job2

But i am receiving error like follows

Receive-Job : The term 'Execute-Build' is not recognized as the name of a cmdle t, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Why this error occurs and how to resolve this?

Upvotes: 2

Views: 1293

Answers (2)

CB.
CB.

Reputation: 60918

Start-Job open a new instance of PowerShell.exe which doesn't have your Execute-Build function. You need to include it in the script block and then call it or use -InitializationScript parameter:

$a = { function myfunction {return "whatever!"} }
$job = Start-Job {myfunction} -InitializationScript $a
Get-Job

Upvotes: 2

Andy Arismendi
Andy Arismendi

Reputation: 52609

The dot sourced code will not be available in the background job.

One way to solve this is to dot source Build.ps1 in the background job like this:

$job1 = Start-Job { 
    . "C:\Path\To\Build.ps1"
    Execute-Build "List.txt" 
}

You can also pass the path as a parameter like this:

$path = (Resolve-Path ./Build.ps1).Path
$job1 = Start-Job {
    param ($ScriptPath)
    . "$ScriptPath"
    Execute-Build "List.txt" 
} -ArgumentList $path

Upvotes: 3

Related Questions