src/Solutions/Components/Copy-XrmSolutionComponents.ps1

<#
    .SYNOPSIS
    Copy Solution Components.

    .DESCRIPTION
    Add all components from source solution to target one.
    A table keeps its behavior: with all its subcomponents (rootcomponentbehavior 0) or without them (1 and 2: added without subcomponents). Root components are added before their subcomponents.
    A component that fails is reported and does not stop the others; one error then lists the failed components (TargetObject: ComponentId, ComponentType, Message per component).

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

    .PARAMETER SourceSolutionUniqueName
    Solution unique name where to get components.

    .PARAMETER TargetSolutionUniqueName
    Unmanaged solution unique name where to add components.

    .OUTPUTS
    System.Void.

    .EXAMPLE
    Copy-XrmSolutionComponents -XrmClient $xrmClient -SourceSolutionUniqueName "contoso_core" -TargetSolutionUniqueName "contoso_hotfix";

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

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

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $SourceSolutionUniqueName,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $TargetSolutionUniqueName
    )
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
    }    
    process {
        
        $sourceComponents = $XrmClient | Get-XrmSolutionComponents -SolutionUniqueName $SourceSolutionUniqueName;
        if (-not $sourceComponents) {
            return;
        }
        # Roots first: a subcomponent listed on its own (table added without its subcomponents) goes after its table
        $sourceComponents = @($sourceComponents | Sort-Object -Property { if ($_.rootsolutioncomponentid_Value) { 1 } else { 0 } });
        $failures = [System.Collections.Generic.List[PSCustomObject]]::new();
        ForEach-ObjectWithProgress -Collection $sourceComponents -OperationName "Solution components copy from $SourceSolutionUniqueName to $TargetSolutionUniqueName" -ScriptBlock {
            param($component)

            $componentType = $component.componenttype_Value.Value;
            $addParameters = @{ XrmClient = $XrmClient; SolutionUniqueName = $TargetSolutionUniqueName; ComponentId = $component.objectid; ComponentType = $componentType; };
            # A table is copied as it is in the source, with or without its subcomponents (it was always added without them) (M22)
            $behavior = $component.rootcomponentbehavior_Value;
            if ($componentType -eq 1 -and $null -ne $behavior) {
                $addParameters["DoNotIncludeSubcomponents"] = ($behavior.Value -ne 0);
            }
            # One failing component does not stop the others (M22). One response per component: not the output of this cmdlet (M41)
            try {
                Add-XrmSolutionComponent @addParameters -ErrorAction Stop | Out-Null;
            }
            catch {
                Write-HostAndLog -Message "Component '$($component.objectid)' (type $componentType) not copied: $($_.Exception.Message)" -Level WARN;
                $failures.Add([PSCustomObject]@{ ComponentId = $component.objectid; ComponentType = $componentType; Message = $_.Exception.Message; });
            }
        }
        if ($failures.Count -gt 0) {
            $details = ($failures | Select-Object -First 5 | ForEach-Object { "$($_.ComponentId) (type $($_.ComponentType)): $($_.Message)" }) -join " | ";
            Write-Error -Message "$($failures.Count) of $($sourceComponents.Count) components not copied to '$TargetSolutionUniqueName'. $details" -TargetObject $failures.ToArray() -Category InvalidResult;
        }
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function Copy-XrmSolutionComponents -Alias *;

Register-ArgumentCompleter -CommandName Copy-XrmSolutionComponents -ParameterName "SourceSolutionUniqueName" -ScriptBlock {

    param($CommandName, $ParameterName, $WordToComplete, $CommandAst, $FakeBoundParameters)

    $solutionUniqueNames = @();
    $solutions = Get-XrmSolutions -Columns "uniquename";
    $solutions | ForEach-Object { $solutionUniqueNames += $_.uniquename };
    return $solutionUniqueNames | Where-Object { $_ -like "$wordToComplete*" } | Sort-Object;
}

Register-ArgumentCompleter -CommandName Copy-XrmSolutionComponents -ParameterName "TargetSolutionUniqueName" -ScriptBlock {

    param($CommandName, $ParameterName, $WordToComplete, $CommandAst, $FakeBoundParameters)

    $solutionUniqueNames = @();
    $solutions = Get-XrmSolutions -Columns "uniquename";
    $solutions | ForEach-Object { $solutionUniqueNames += $_.uniquename };
    return $solutionUniqueNames | Where-Object { $_ -like "$wordToComplete*" } | Sort-Object;
}