src/Plugins/Upsert-XrmAssembly.ps1

<#
    .SYNOPSIS
    Create or update plugin / workflow assembly.

    .DESCRIPTION
    Add new or update existing assembly content from local dll file.

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

    .PARAMETER AssemblyPath
    Full file path to dll. A relative path is read from the PowerShell location.

    .PARAMETER SolutionUniqueName
    Microsoft Dataverse solution unique name where to add new assembly.

    .PARAMETER IsolationMode
    Specify if assembly will be deploy in sandbox or not, on creation only. (Default = 2 | 1 = Not sandboxed, 2 = Sandbox)

    .PARAMETER SourceType
    Specify where assembly will be stored, on creation only. (Default = 0 | 0 = Database, 1 = Disk, 2 = Normal (OnPremise), 3 = AzureWebApp)

    .OUTPUTS
    Microsoft.Xrm.Sdk.EntityReference. Reference of the created or updated assembly.

    .EXAMPLE
    $xrmClient = New-XrmClient -ConnectionString $connectionString;
    $xrmClient | Upsert-XrmAssembly -AssemblyPath "C:\Sources\Contoso.Plugins\bin\Release\Contoso.Plugins.dll" -SolutionUniqueName "contoso_core";

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

function Upsert-XrmAssembly {
    [CmdletBinding(SupportsShouldProcess)]    
    [OutputType([Microsoft.Xrm.Sdk.EntityReference])]
    param
    (        
        [Parameter(Mandatory = $false, ValueFromPipeline)]
        [Microsoft.PowerPlatform.Dataverse.Client.ServiceClient]
        $XrmClient = $Global:XrmClient,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [ValidateScript( { Test-Path $_ })]
        [string]
        $AssemblyPath,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]
        $SolutionUniqueName,

        [Parameter(Mandatory = $false)]
        [int]
        $IsolationMode = 2, # Sandbox

        [Parameter(Mandatory = $false)]
        [int]
        $SourceType = 0 # Database
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);       
    }    
    process {
        # Relative to the PowerShell location, not to the folder of the process (M25)
        if ($AssemblyPath) { $AssemblyPath = Resolve-XrmPathInternal -Path $AssemblyPath; }
        
        # Name, version, culture and token read from the file without loading the assembly into the session (B24)
        $assemblyName = [System.Reflection.AssemblyName]::GetAssemblyName($AssemblyPath);
        $assemblyProperties = $assemblyName.FullName.Split(",=".ToCharArray(), [StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object { $_.Trim() };
        $assemblyShortName = $assemblyProperties[0];
        $assemblyContent = Get-XrmBase64 -FilePath $AssemblyPath;

        $existingAssembly = Get-XrmRecord -XrmClient $XrmClient -LogicalName "pluginassembly" -AttributeName "name" -Value $assemblyShortName;
        if (-not $existingAssembly) {
            $assemblyRecord = New-XrmEntity -LogicalName "pluginassembly" -Attributes @{
                name           = $assemblyProperties[0]
                version        = $assemblyProperties[2]
                culture        = $assemblyProperties[4]
                publickeytoken = $assemblyProperties[6]
                content        = $assemblyContent
                sourcetype     = (New-XrmOptionSetValue -Value $SourceType)
                isolationmode  = (New-XrmOptionSetValue -Value $IsolationMode)
            };
            $createdId = $XrmClient | Add-XrmRecord -Record $assemblyRecord;
            # Skipped by -WhatIf, or failed (the error is already written)
            if (-not $createdId) {
                return;
            }
            $assemblyRecord.Id = $createdId;
        }
        else {
            $assemblyRecord = New-XrmEntity -LogicalName "pluginassembly" -Id $existingAssembly.Id -Attributes @{
                version        = $assemblyProperties[2]
                culture        = $assemblyProperties[4]
                publickeytoken = $assemblyProperties[6]
                content        = $assemblyContent
            };
            $XrmClient | Update-XrmRecord -Record $assemblyRecord;
        }
        if ($PSBoundParameters.SolutionUniqueName) {
            $componentType = Get-XrmSolutionComponentType -XrmClient $XrmClient -LogicalName "pluginassembly";
            Add-XrmSolutionComponent -XrmClient $XrmClient -ComponentId $assemblyRecord.Id -ComponentType $componentType -SolutionUniqueName $SolutionUniqueName | Out-Null;
        }
        $assemblyRecord.ToEntityReference();
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function Upsert-XrmAssembly -Alias *;