Search code examples
powershellstart-job

Powershell dynamic Start-Job command to execute all powershell scripts in subfolders in parallel


For an important data migration, I would like to execute in parallel multiple scripts in side subfolders :

I did not succeed to do this :

$folders = Get-ChildItem -Directory

foreach($folder in $folders){
    $cmd = "powershell '$folder\script.ps1'"
    $job = start-job -ScriptBlock {Invoke-Expression $cmd}
}

folder estructure

Thank you for your help!


Solution

  • You can use Invoke-Command for concurrent processing. Here's an example that may meet your requirements.

    Get-ChildItem -Directory | ForEach-Object {
        $folderPath = $_.FullName
        Start-Job -ScriptBlock { .\script.ps1 $using:folderPath }
    }
    
    Get-Job | ForEach-Object {
        $result = Wait-Job $_ | Receive-Job
        Remove-Job $_
        $result
    }