1

I got my main.ps1 script with a loop calling a sub.ps1. Currently I wait until the end of sub.ps1 to run the next one.

I would like to do some parallel processing, only in the case that it takes too long. Some subtleties: I can't edit sub.ps1 and I set env variables in main.ps1 for sub.ps1.

So I came out with the this first idea :

  • creating an intermedate shell to run sub.ps1 and raise an event at its end
  • wait that event in main.ps1 with a timeout

but not quite convinced, so I tried with Start-job and Wait-job, but doesn't work.

It shows the job ending instantly, not minding the sleep in inter_shell.ps1 and continue the loop. Also I'm not sure if it share the env variable.

I can't much share the code so here is some aproximations

main.ps1

# set dummy env var
$env:var1 = "aze"

# wait at least that time before start new process
$timeout = 10

# simulate the n process stack to run
for($i = 7; $i -lt 14; $i++) {

    Write-Host "start $i"

    # run intermediate shell that will run sub.ps1
    $jobName = "Inter_$i"
    Get-Date 
    $a = Start-Job -Name $jobName -ScriptBlock {powershell .\inter_shell.ps1 -workTime $i}
    Get-Date 
    $a | Wait-Job -Timeout $timeout
    Get-Date 
}

inter_shell.ps1

param([int] $workTime)

$env:var1
# Simulate sub.ps1 process
Start-Sleep -Seconds $workTime
Adriaan
  • 17,741
  • 7
  • 42
  • 75
Simon
  • 11
  • 2
  • `Start-Job` already creates a new PowerShell process on its own. To me it doesn't make much sense to start a PowerShell instance again from the job. I would just do `Start-Job -FilePath inter_shell.ps1 ...`. – zett42 Dec 03 '22 at 17:32
  • Thanks @zett42, that was it. I changed the `Start-job` line to `$a = Start-Job -Name $eventName -FilePath .\inter_shell.ps1 -ArgumentList $i` and it runs as expeted. I still need to check the env variable. – Simon Dec 05 '22 at 08:28
  • The env variable should work. Env vars are automatically inherited by child processes. – zett42 Dec 05 '22 at 08:49
  • Please do not add answers to the question body itself. Instead, you should add it as an answer. [Answering your own question is allowed and even encouraged](https://stackoverflow.com/help/self-answer). – Adriaan Dec 07 '22 at 08:58
  • I'm on it. Also I figured out the edit is wrong.. – Simon Dec 07 '22 at 09:10

0 Answers0