Foreach-object -Parallel - Correct way of doing it?

Hi :slight_smile:

I want to leverage / learn more about the Foreach-Object -Parallel parameter, to speed up our SQL backups. I basically want it to process multiple SQLInstances, but only perform a backup of one database per instance - so that we dont overload the instance itself.

So i made a simple example that actually does what i expected it to do:

$SQLInfo = @(
    @{
        'SQLInstance' = 'dk1sql01'
    },
    @{
        'SQLInstance' = 'dk1sql02'
    }
)

$JobVar = $SQLInfo | ForEach-Object -ThrottleLimit 10 -Parallel {
    $SQLConn = Connect-DbaInstance -SqlInstance $_.SQLInstance
    $Databases = Get-DbaDatabase -SqlInstance $SQLConn -ExcludeSystem
    foreach ($Database in $Databases) {
        try {
            $TempVar = Backup-DbaDatabase -SqlInstance $SQLConn -Database $Database.Name -FilePath "K:\Backup" -CreateFolder -ErrorAction stop -WarningAction stop    
            [PSCustomObject]@{
                SQLInstance      = $SQLConn.Name
                Database         = $Database.Name
                Start            = $TempVar.Start
                BackupOK         = $true
                ExceptionMessage = $null
            }
        }
        catch {
            [PSCustomObject]@{
        
                SQLInstance      = $SQLConn.Name
                Database         = $Database.Name
                Start            = $TempVar.Start
                BackupOK         = $false
                ExceptionMessage = $_.Exception.Message
            }
        }
    }
    $SQLConn | Disconnect-DbaInstance -Confirm:$false -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Out-Null
} -AsJob


#Get the status
$JobArray = @()
$Jobs = Get-Job -id $JobVar.Id -IncludeChildJob | Wait-Job
foreach ($Job in $Jobs.ChildJobs ) {
    $JobArray += Receive-Job -Job $job -Keep
}

#Present the data
$JobArray | Out-GridView

The output can then easily be shipped to Jira, and then processed there if something should be handled.

But am i doing the -Parallel part correctly? Ive read alot about race conditions, etc - so i wanted to make sure, that this is correct :slight_smile: