johnnygear
johnnygear

Reputation: 93

Powershell: Recursive Functions and Multiple Parameters in Start-Job

I have been banging my head against a wall for a couple of days now trying to get Start-Job and background jobs working to no avail.

I have tried ScriptBlock and ScriptFile but neither seem to do what I want, or I can't seem to get the syntax right.

I have a number of recursive functions and need to split up the script to work in parallel accross many chunks of a larger data set.

No matter how I arrange the Start-Job call, nothing seems to work, and the recursive functions seem to be making everything twice as hard.

Can anyone give me a working example of Start-Job calling a recursive function and having multiple parameters, or point me somewhere where one exists?

Any help appreciated

Upvotes: 0

Views: 1310

Answers (1)

Keith Hill
Keith Hill

Reputation: 201672

This works for me:

$sb = {param($path, $currentDepth, $maxDepth) function EnumFiles($dir,$currentDepth,$maxDepth) { if ($currentDepth -gt $maxDepth) { return }; Get-ChildItem $dir -File; Get-ChildItem $dir -Dir | Foreach {EnumFiles $_.FullName ($currentDepth+1) $maxDepth}}; EnumFiles $path $currentDepth $maxDepth }
$job = Start-Job -ScriptBlock $sb -ArgumentList $pwd,0,2
Wait-Job $job | Out-Null
Receive-Job $job

Keep in mind your functions have to be defined in the scriptblock because the script runs in a completely separate PowerShell process. Same goes for any externally defined variables - they have to be passed into Start-Job via the -ArgumentList parameter. The values will be serialized, passed to the PowerShell process executing the job, where they will then be provided to the scriptblock.

Upvotes: 2

Related Questions