src/WebResources/Sync-XrmWebResources.ps1

<#
    .SYNOPSIS
    Synchronize a webresource folder to Microsoft Dataverse.

    .DESCRIPTION
    Create or update each webresource content based on local directory.
    A file that fails is reported and does not stop the others; the webresources created or updated are published, then one error lists the failed files (TargetObject: FilePath, Message per file).

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

    .PARAMETER FolderPath
    Full path to directory where webresources are stored.

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

    .PARAMETER SynchronizationMode
    Specify synchronization pattern : full or delta. (Default: Delta)
    Full will update all webresources.
    Delta will only update changed webresource based on SynchronizationDeltaHours parameter.

    .PARAMETER SynchronizationDeltaHours
    Use this parameter with SynchronizationMode = Delta, take local files modified during last x hours. (Default : 4 hours)

    .PARAMETER SupportedExtensions
    Specify file extensions to handle in synchronization process. (Default : htm, html, css, js, xml, png, jpg, jpeg, gif, xap, xsl, ico, svg, resx)

    .OUTPUTS
    System.Void. Each file is reported on the host; the updated webresources are published at the end, failures included.

    .EXAMPLE
    $xrmClient = New-XrmClient -ConnectionString $connectionString;
    $xrmClient | Sync-XrmWebResources -FolderPath "C:\Sources\Contoso\WebResources" -SolutionUniqueName "contoso_core" -SynchronizationMode Delta -SynchronizationDeltaHours 1;

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


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

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

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

        [Parameter(Mandatory = $false)]
        [ValidateSet("Full", "Delta")]
        [ValidateNotNullOrEmpty()]
        [string]
        $SynchronizationMode,

        [Parameter(Mandatory = $false)]
        [int]
        $SynchronizationDeltaHours = 4,

        [Parameter(Mandatory = $false)]
        [string[]]
        $SupportedExtensions = @("*.htm", "*.html", "*.css", "*.js", "*.xml", "*.png", "*.jpg", "*.jpeg", "*.gif", "*.xap", "*.xsl", "*.ico", "*.svg", "*.resx")
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);       
    }    
    process {
        
        # Resolve publisher prefix for given solution
        $solution = $XrmClient | Get-XrmRecord -LogicalName "solution" -AttributeName "uniquename" -Value $SolutionUniqueName -Columns "publisherid";
        $publisher = $XrmClient | Get-XrmRecord -LogicalName "publisher" -Id $solution.publisherid_Value.Id -Columns "customizationprefix";
        $prefix = "$($publisher.customizationprefix)_";
                
        # Collected through a reference type: the ForEach-ObjectWithProgress scriptblock runs in a child scope
        $changedWebResourceIds = [System.Collections.Generic.List[Guid]]::new();
        $failures = [System.Collections.Generic.List[PSCustomObject]]::new();

        # Load last modified webresources and process files
        $fullSync = ($SynchronizationMode -eq "Full");
        if ($fullSync) {
            $delta = [DateTime]::MinValue;
        }
        else {
            $now = [DateTime]::Now;
            $delta = $now.AddHours($SynchronizationDeltaHours * -1);
        }
        $webResourceFilePaths = Get-ChildItem $FolderPath -recurse -include $SupportedExtensions | where-object { $_.mode -notmatch "d" } | where-object { ($_.lastwritetime -gt $delta) }; 

        ForEach-ObjectWithProgress -Collection $webResourceFilePaths -OperationName "Synchronize Webresources" -ScriptBlock {
            param($webResourceFilePath)

            if ($webResourceFilePath.PSIsContainer) { return; }

            $webResourcePath = $webResourceFilePath.FullName;
            $webResourceName = $webResourceFilePath.Name;

            Write-HostAndLog " > Processing webresource " -NoNewline -NoTimeStamp -ForegroundColor Gray;
            Write-HostAndLog $webResourceName -NoNewline -NoTimeStamp -ForegroundColor Yellow;
            Write-HostAndLog " ..." -NoNewline -NoTimeStamp -ForegroundColor Gray;
            
            # One failing file does not stop the others, nor the publish of those already updated (M24)
            try {
                $webresourceId = Upsert-XrmWebResource -XrmClient $XrmClient -FilePath $webResourcePath -SolutionUniqueName $SolutionUniqueName -Prefix $prefix -ErrorAction Stop;
            }
            catch {
                Write-HostAndLog "[Error] $($_.Exception.Message)" -NoTimeStamp -ForegroundColor Red;
                $failures.Add([PSCustomObject]@{ FilePath = $webResourcePath; Message = $_.Exception.Message; });
                return;
            }
            if ($webresourceId) {
                Write-HostAndLog "[OK]" -NoTimeStamp -ForegroundColor Green;
                $changedWebResourceIds.Add($webresourceId);
            }
            else {
                Write-HostAndLog "[Skipped]" -NoTimeStamp -ForegroundColor DarkGray;
            }
        }
        if ($changedWebResourceIds.Count -gt 0) {
            Publish-XrmComponent -XrmClient $XrmClient -ComponentName "webresource" -ComponentId @($changedWebResourceIds | ForEach-Object { "$_" }) | Out-Null;
        }
        if ($failures.Count -gt 0) {
            $details = ($failures | Select-Object -First 5 | ForEach-Object { "$($_.FilePath): $($_.Message)" }) -join " | ";
            Write-Error -Message "$($failures.Count) webresource file(s) failed. $details" -TargetObject $failures.ToArray() -Category InvalidResult;
        }
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function Sync-XrmWebResources -Alias *;