3

Is there any way to run parallel programmed functions in PowerShell?

Something like:

Function BuildParallel($configuration)
{
    $buildJob = {
        param($configuration)
        Write-Host "Building with configuration $configuration."
        RunBuilder $configuration;
    }

    $unitJob = {
        param()
        Write-Host "Running unit."
        RunUnitTests;
    }

    Start-Job $buildJob -ArgumentList $configuration
    Start-Job $unitJob

    While (Get-Job -State "Running")
    {
        Start-Sleep 1
    }

    Get-Job | Receive-Job
    Get-Job | Remove-Job
}

Does not work because it complains about not recognizing "RunUnitTests" and "RunBuilder", which are functions declared in the same script file. Apparently this happens because the script block is a new context and does not know anything about the scripts declared in the same file.

I could try to use -InitializationScript in Start-Job, but both RunUnitTests and RunBuilder call more functions declared in the same file or referred from other files, so...

I'm sure there's a way to do this, since it's just modular programming (functions, routines and all that stuff).

1 Answer 1

1

You could have the functions in a separate file and import them into the current context wherever needed via dot sourcing. I do this in my Powershell profile, so some of my custom functions are available.

$items = Get-ChildItem "$PSprofilePath\functions"
$items | ForEach-Object {
    . $_.FullName
}  

If you wanted import one file, it would just be:

. C:\some\path\RunUnitTests.ps1
Sign up to request clarification or add additional context in comments.

2 Comments

But should I use that inside the ScriptBlock and functions will be automatically recognized?
Correct, the ScriptBlock/job is runs in it's own context, so you would run it at the start of each scriptblock to import your functions into that job's context.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.