src/Client/Join-XrmRecords.ps1

<#
    .SYNOPSIS
    Associate records in Dataverse.

    .Description
    Add a link between 1 row (Entity record) and multiple rows in Microsoft Dataverse.

    .PARAMETER XrmClient
    Xrm connector initialized to target instance. Use latest one by default. (Dataverse ServiceClient)

    .PARAMETER RecordReference
    Reference of the row to link the others to. (EntityReference)

    .PARAMETER RecordReferences
    Rows / Records references to link to Record. (EntityReference array)

    .PARAMETER RelationShipName
    RelationShip Logical name involve between these records.

    .PARAMETER RelationShipRole
    Role of RecordReference when the relationship links a table to itself: Referencing or Referenced. (Default: Referencing)

    .PARAMETER IgnoreExistings
    Prevent exceptions if record associations already exist (error => Cannot insert duplicate key). When several references are given and one link already exists, the platform refuses the whole request: the references are then associated one by one, the existing links skipped. (Default: true)

    .OUTPUTS
    System.Void.

    .EXAMPLE
    $account = Get-XrmRecord -LogicalName "account" -Id $accountId;
    $contactRefs = @(New-XrmEntityReference -LogicalName "contact" -Id $contactId);
    Join-XrmRecords -RecordReference $account.Reference -RecordReferences $contactRefs -RelationShipName "contact_customer_accounts";

    .LINK
    https://github.com/AymericM78/PowerDataOps/blob/main/documentation/commands/Join-XrmRecords.md
#>

function Join-XrmRecords {
    [CmdletBinding(SupportsShouldProcess)]
    [OutputType([System.Void])]
    param
    (    
        [Parameter(Mandatory = $false, ValueFromPipeline)]
        [Microsoft.PowerPlatform.Dataverse.Client.ServiceClient]
        $XrmClient = $Global:XrmClient,

        [Parameter(Mandatory = $true)]
        [Microsoft.Xrm.Sdk.EntityReference]
        $RecordReference,

        [Parameter(Mandatory = $true)]
        [Microsoft.Xrm.Sdk.EntityReference[]]
        $RecordReferences,

        [Parameter(Mandatory = $true)]
        [string]
        $RelationShipName,

        [Parameter(Mandatory = $false)]
        [Microsoft.Xrm.Sdk.EntityRole]
        $RelationShipRole = [Microsoft.Xrm.Sdk.EntityRole]::Referencing,

        [Parameter(Mandatory = $false)]
        [bool]
        $IgnoreExistings = $true        
    )
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);
    }    
    process {

        $relationShip = New-Object -TypeName "Microsoft.Xrm.Sdk.Relationship" -ArgumentList $RelationShipName;        
        $relationShip.PrimaryEntityRole = $RelationShipRole;

        $recordReferenceCollection = New-XrmEntityReferenceCollection -EntityReferences @($RecordReferences);

        try {
            $associateRequest = [Microsoft.Xrm.Sdk.Messages.AssociateRequest]::new();
            $associateRequest.Target = $RecordReference;
            $associateRequest.Relationship = $relationShip;
            $associateRequest.RelatedEntities = $recordReferenceCollection;
            $XrmClient | Invoke-XrmRequest -Request $associateRequest | Out-Null;
        }
        catch {
            if (-not ($IgnoreExistings -and $_.Exception.Message.Contains("Cannot insert duplicate key"))) {
                throw $_.Exception;
            }
            if ($RecordReferences.Count -le 1) {
                return;
            }
            # One existing link cancels the whole request: associate the references one by one, skipping the existing links (M18)
            foreach ($singleReference in $RecordReferences) {
                try {
                    $singleRequest = [Microsoft.Xrm.Sdk.Messages.AssociateRequest]::new();
                    $singleRequest.Target = $RecordReference;
                    $singleRequest.Relationship = $relationShip;
                    $singleRequest.RelatedEntities = New-XrmEntityReferenceCollection -EntityReferences @($singleReference);
                    $XrmClient | Invoke-XrmRequest -Request $singleRequest | Out-Null;
                }
                catch {
                    if (-not $_.Exception.Message.Contains("Cannot insert duplicate key")) {
                        throw $_.Exception;
                    }
                }
            }
        }
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function Join-XrmRecords -Alias *;