src/AzDevOps/BuildTasks/Export-XrmSolutionsBuild.ps1

<#
    .SYNOPSIS
    Run build action to export solutions.

    .DESCRIPTION
    This cmdlet is designed to be fully intergrated in Az DevOps pipeline.
    This cmdlet export given solutions in order to add them to build artifacts.
    The source environment is only read, unless ClearCreateStepFilteringAttributes is true.

    .PARAMETER ConnectionString
    Target instance connection string, use variable 'ConnectionString' from associated variable group.

    .PARAMETER ExportPath
    Folder path where solutions will be exported. (Default: Agent Artifacts Staging directory)

    .PARAMETER Solutions
    Solution uniquenames that will be exported and then unpacked, use variable 'Solutions' from associated variable group.

    .PARAMETER Managed
    Specify if solution should be export as managed or unmanaged. (Default: true = managed)

    .PARAMETER ExportCalendarSettings
    Specify if exported solution should include Calendar settings (Default: false)

    .PARAMETER ExportCustomizationSettings
    Specify if exported solution should include Customization settings (Default: false)

    .PARAMETER ExportEmailTrackingSettings
    Specify if exported solution should include Email Tracking settings (Default: false)

    .PARAMETER ExportAutoNumberingSettings
    Specify if exported solution should include AutoNumbering settings (Default: false)

    .PARAMETER ExportIsvConfig
    Specify if exported solution should include Isv settings (Default: false)

    .PARAMETER ExportOutlookSynchronizationSettings
    Specify if exported solution should include Outlook Synchronization settings (Default: false)

    .PARAMETER ExportGeneralSettings
    Specify if exported solution should include General settings (Default: false)

    .PARAMETER ExportMarketingSettings
    Specify if exported solution should include Marketing settings (Default: false)

    .PARAMETER ExportRelationshipRoles
    Specify if exported solution should include RelationshipRoles (Default: false)

    .PARAMETER ForceSyncExport
    Export with the synchronous ExportSolution message instead of the asynchronous one. (Default: asynchronous export)

    .PARAMETER ClearCreateStepFilteringAttributes
    Before the export, clear the filtering attributes of the plug-in steps registered on the Create message, in the source environment. Only the unmanaged steps that belong to the exported solutions are updated (filtering attributes only apply to Update; a Create step that has some failed to import in 2022). (Default: false = the source environment is not modified)

    .PARAMETER XrmClient
    Xrm connector initialized to source instance, used instead of ConnectionString. (Default: a connection opened with ConnectionString)

    .OUTPUTS
    System.Void. Progress is written to the host and to the log.

    .EXAMPLE
    Export-XrmSolutionsBuild -ConnectionString $connectionString -ExportPath "C:\drop" -Solutions "contoso_core,contoso_sales" -Managed $true;

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

function Export-XrmSolutionsBuild {
    [CmdletBinding(SupportsShouldProcess)]
    [OutputType([System.Void])]
    param
    (
        [Parameter(Mandatory = $false)]
        [String]
        $ConnectionString = $env:CONNECTIONSTRING,

        [Parameter(Mandatory = $false)]
        [String]
        $ExportPath = $env:BUILD_ARTIFACTSTAGINGDIRECTORY,

        [Parameter(Mandatory = $false)]
        [String]
        $Solutions = $env:SOLUTIONS,

        [Parameter(Mandatory = $false)]
        [Boolean]
        $Managed = $true,

        [Parameter(Mandatory = $false)]
        [Boolean]
        $ExportCalendarSettings = $false,

        [Parameter(Mandatory = $false)]
        [Boolean]
        $ExportCustomizationSettings = $false,

        [Parameter(Mandatory = $false)]
        [Boolean]
        $ExportEmailTrackingSettings = $false,

        [Parameter(Mandatory = $false)]
        [Boolean]
        $ExportAutoNumberingSettings = $false,

        [Parameter(Mandatory = $false)]
        [Boolean]
        $ExportIsvConfig = $false,

        [Parameter(Mandatory = $false)]
        [Boolean]
        $ExportOutlookSynchronizationSettings = $false,

        [Parameter(Mandatory = $false)]
        [Boolean]
        $ExportGeneralSettings = $false,

        [Parameter(Mandatory = $false)]
        [Boolean]
        $ExportMarketingSettings = $false,

        [Parameter(Mandatory = $false)]
        [Boolean]
        $ExportRelationshipRoles = $false,

        [Parameter(Mandatory = $false)]
        [switch]
        $ForceSyncExport = $false,

        [Parameter(Mandatory = $false)]
        [Boolean]
        $ClearCreateStepFilteringAttributes = $false,

        [Parameter(Mandatory = $false)]
        [Microsoft.PowerPlatform.Dataverse.Client.ServiceClient]
        $XrmClient
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);
    }
    process {

        if (-not $XrmClient) {
            $XrmClient = New-XrmClient -ConnectionString $ConnectionString;
        }

        Write-HostAndLog -Message " - Param : Export path = $ExportPath" -Level INFO;
        Write-HostAndLog -Message " - Param : Managed = $Managed" -Level INFO;
        Write-HostAndLog -Message " - Param : Solutions = $Solutions" -Level INFO;
        Write-HostAndLog -Message " - Param : ExportCalendarSettings = $ExportCalendarSettings" -Level INFO;
        Write-HostAndLog -Message " - Param : ExportCustomizationSettings = $ExportCustomizationSettings" -Level INFO;
        Write-HostAndLog -Message " - Param : ExportEmailTrackingSettings = $ExportEmailTrackingSettings" -Level INFO;
        Write-HostAndLog -Message " - Param : ExportAutoNumberingSettings = $ExportAutoNumberingSettings" -Level INFO;
        Write-HostAndLog -Message " - Param : ExportIsvConfig = $ExportIsvConfig" -Level INFO;
        Write-HostAndLog -Message " - Param : ExportOutlookSynchronizationSettings = $ExportOutlookSynchronizationSettings" -Level INFO;
        Write-HostAndLog -Message " - Param : ExportGeneralSettings = $ExportGeneralSettings" -Level INFO;
        Write-HostAndLog -Message " - Param : ExportMarketingSettings = $ExportMarketingSettings" -Level INFO;
        Write-HostAndLog -Message " - Param : ExportRelationshipRoles = $ExportRelationshipRoles" -Level INFO;
        Write-HostAndLog -Message " - Param : ClearCreateStepFilteringAttributes = $ClearCreateStepFilteringAttributes" -Level INFO;

        $solutionList = @($Solutions.Split(",") | ForEach-Object { $_.Trim() } | Where-Object { $_ });

        # =========================================================================================================
        # Opt-in: filtering attributes of the Create steps of the exported solutions (source environment updated)
        # =========================================================================================================
        if ($ClearCreateStepFilteringAttributes) {
            Write-HostAndLog -Message "Clearing filtering attributes of the Create steps of the exported solutions" -Level INFO;

            $solutionQuery = New-XrmQueryExpression -LogicalName "solution" -Columns "uniquename";
            $solutionQuery = $solutionQuery | Add-XrmQueryCondition -Field "uniquename" -Condition In -Values $solutionList;
            $solutionIds = @($XrmClient | Get-XrmMultipleRecords -Query $solutionQuery -AsArray | ForEach-Object { $_.Id });

            $stepComponentType = Get-XrmSolutionComponentType -XrmClient $XrmClient -LogicalName "sdkmessageprocessingstep";
            # Distinct (a step may belong to several exported solutions): the primary key is only returned when asked for
            $query = New-XrmQueryExpression -LogicalName "sdkmessageprocessingstep" -Columns "sdkmessageprocessingstepid", "name";
            $query.Distinct = $true;
            $query = $query | Add-XrmQueryCondition -Field "filteringattributes" -Condition NotNull;
            $query = $query | Add-XrmQueryCondition -Field "ismanaged" -Condition Equal -Values $false;
            $messageLink = $query | Add-XrmQueryLink -ToEntityName "sdkmessage" -FromAttributeName "sdkmessageid" -ToAttributeName "sdkmessageid";
            $messageLink | Add-XrmQueryLinkCondition -Field "name" -Condition Equal -Values "Create" | Out-Null;
            $componentLink = $query | Add-XrmQueryLink -ToEntityName "solutioncomponent" -FromAttributeName "sdkmessageprocessingstepid" -ToAttributeName "objectid";
            $componentLink | Add-XrmQueryLinkCondition -Field "componenttype" -Condition Equal -Values $stepComponentType | Out-Null;
            $componentLink | Add-XrmQueryLinkCondition -Field "solutionid" -Condition In -Values $solutionIds | Out-Null;

            $steps = $XrmClient | Get-XrmMultipleRecords -Query $query -AsArray;
            $updatedCount = 0;
            foreach ($step in $steps) {
                Write-HostAndLog -Message " > Step '$($step.name)' contains filtering attributes" -Level WARN;
                $stepUpdate = New-XrmEntity -LogicalName "sdkmessageprocessingstep" -Id $step.Id -Attributes @{
                    "filteringattributes" = $null;
                };
                try {
                    $XrmClient | Update-XrmRecord -Record $stepUpdate -ErrorAction Stop;
                    if (-not $WhatIfPreference) {
                        $updatedCount++;
                    }
                }
                catch {
                    Write-HostAndLog -Message " > Unable to update step '$($step.name)': $($_.Exception.Message)" -Level WARN;
                }
            }
            Write-HostAndLog -Message "$updatedCount of $($steps.Count) step(s) updated" -Level WARN;
        }

        foreach ($solutionUniqueName in $solutionList) {
            Write-HostAndLog -Message "Exporting solution $solutionUniqueName" -Level INFO;
            $solutionFilePath = $XrmClient | Export-XrmSolution -SolutionUniqueName $solutionUniqueName -Managed $Managed -ExportPath $ExportPath -ExportCalendarSettings $ExportCalendarSettings -ExportCustomizationSettings $ExportCustomizationSettings -ExportEmailTrackingSettings $ExportEmailTrackingSettings -ExportAutoNumberingSettings $ExportAutoNumberingSettings -ExportIsvConfig $ExportIsvConfig -ExportOutlookSynchronizationSettings $ExportOutlookSynchronizationSettings -ExportGeneralSettings $ExportGeneralSettings -ExportMarketingSettings $ExportMarketingSettings -ExportRelationshipRoles $ExportRelationshipRoles -ForceSyncExport:$ForceSyncExport;
            Write-HostAndLog -Message "Solution $solutionUniqueName successfully exported to '$solutionFilePath' !" -Level SUCCESS;

            if ($env:SLACKURL) {
                Write-XrmMessageToSlack -Message "Solution $solutionUniqueName successfully exported to '$solutionFilePath' !";
            }
        }
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }
}

Export-ModuleMember -Function Export-XrmSolutionsBuild -Alias *;