powershellfunctionparametersstart-job

How do I use Start- Job to start a function with parameters stored in another ps1?


the ps1 containing the function:

function MyFunction ($path) {
#does something
}

the ps1 calling the function:

Import-Module .\FunctionParent.ps1
$job = Start-Job -ArgumentList $PSScriptRoot -FilePath "MyFunction .ps1"

$dll = $PSScriptRoot+'\Interop.CCProjectMgrLib.dll'
Write-Host $dll -foreground Yellow

Start-Sleep 5

$JobStatus = $job.State
Write-Host $job.State -foreground Yellow

noob question I know but how do I call the start-job command properly?


Solution

  • Pass a scriptblock to Start-Job, then make sure to dot-source the script before calling the function:

    Start-Job -ScriptBlock {
      param($RootPath)
    
      # dot-source script
      . (Join-Path $RootPath -ChildPath MyFunction.ps1)
    
      # invoke function
      MyFunction -Path $RootPath
    } -ArgumentList $PSScriptRoot