src/Client/Update-XrmRecordFileUpload.ps1

<#
    .SYNOPSIS
    Upload a file to an entity record's file attribute field in Microsoft Dataverse.

    .Description
    Upload a file to a data row's (entity record's) file field from Microsoft Dataverse table.
    The file is sent in blocks of 4 MB (InitializeFileBlocksUpload, UploadBlock, CommitFileBlocksUpload).

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

    .PARAMETER Record
    Record (row) to update.

    .PARAMETER FileAttributeLogicalName
    Entity file attribute name.

    .PARAMETER FilePath
    Path to file on the OS file system. A relative path is read from the PowerShell location.

    .OUTPUTS
    Microsoft.Xrm.Sdk.OrganizationResponse. The CommitFileBlocksUpload response: FileId and FileSizeInBytes of the stored file.

    .EXAMPLE
    $xrmClient = New-XrmClient -ConnectionString $connectionString;
    # Create a new record of a table that has a file column with the logical name new_document
    $entityRecord = New-XrmEntity -LogicalName "new_documentstore" -Attributes @{
        "new_name" = "file1";
    };
    $entityRecord.Id = $xrmClient | Add-XrmRecord -Record $entityRecord;
    Update-XrmRecordFileUpload -XrmClient $xrmClient -Record $entityRecord -FileAttributeLogicalName "new_document" -FilePath 'C:\temp\test.docx';

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

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

        [Parameter(Mandatory = $true, ValueFromPipeline)]
        [Microsoft.Xrm.Sdk.Entity]
        $Record,        

        [Parameter(Mandatory = $true)]
        [String]
        $FileAttributeLogicalName,

        [Parameter(Mandatory = $true)]
        [String]
        $FilePath
    )

    process 
    {
        # Relative to the PowerShell location, not to the folder of the process (M25)
        if ($FilePath) { $FilePath = Resolve-XrmPathInternal -Path $FilePath; }
        # Created based on C# code exmaple from: https://gist.github.com/huseyinzengin91/8cbaa0ae3d11d985676560bbf470564f

        # File upload block size is limitted to 4MB
        $blockSizeByteLimit = 4194304
        $contentType = "application/octet-stream"

        $entityLogicalName = $Record.ToEntityReference().LogicalName
        [Guid]$recordId = $Record.ToEntityReference().Id

        # Get the filename from the filePath
        $fileName = [System.IO.Path]::GetFileName($FilePath)
        
        # # Lookup file's content type
        # # As of 2021-04-02 setting the content type to a value other than "application/octet-stream", doesn't change the content-type returned when downloading the file.
        # $fileExtension = [System.IO.Path]::GetExtension($FilePath)
        # Add-Type -AssemblyName "System.Web"
        # $contentType = [System.Web.MimeMapping]::GetMimeMapping($FilePath)

        # get the file size and calcualte the number of required parts
        $fileInfo = New-Object System.IO.FileInfo($FilePath)
        $totalFileBlocks = [int]($fileInfo.Length / $blockSizeByteLimit) + 1

        $fileBlockCounter = 0
        $fileBuffer = New-Object Byte[] $blockSizeByteLimit
        $fileHasMoreData = $true

        # Keep an array of Block IDs to pass as part of the commit.
        $blockIds = [System.Collections.Generic.List[String]]::new()

        # Init file blocks upload request
        # TODO : Use Web API Function => https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/initializefileblocksupload?view=dataverse-latest
        $initFileBlocksUploadRequest = [Microsoft.Crm.Sdk.Messages.InitializeFileBlocksUploadRequest]::new()
        $initFileBlocksUploadRequest.FileAttributeName = $FileAttributeLogicalName
        $initFileBlocksUploadRequest.FileName = $fileName
        $initFileBlocksUploadRequest.Target = $Record.ToEntityReference()

        $initResponse = $XrmClient | Invoke-XrmRequest -Request $initFileBlocksUploadRequest
        if (-not $initResponse) {
            # Skipped by -WhatIf: no upload started (B15: the blocks were sent with an empty token)
            if ($WhatIfPreference) {
                return;
            }
            throw "The upload of '$fileName' to '$FileAttributeLogicalName' could not be started (see the previous error).";
        }
        $fileContinuationToken = $initResponse.FileContinuationToken

        # Read the file one chunk at a time; the reader is closed even when a block fails (B15)
        $fileReader = [System.IO.File]::OpenRead($FilePath)
        try {
            # Read file blocks until there is no more data
            while ($fileHasMoreData)
            {
                # read a chuck of data form the file
                $fileBytesRead = $fileReader.Read($fileBuffer, 0, $fileBuffer.Length)
                $fileDataBlock = $fileBuffer

                # check if we read less than a full block of data from the file
                if($fileBytesRead -ne $fileBuffer.Length)
                {
                    # If yes, then there is no more file data to read
                    $fileHasMoreData = $false
                    # truncate the output arrat to the number of bytes read
                    $fileDataBlock = New-Object Byte[] $fileBytesRead
                    [System.Array]::Copy($fileBuffer, $fileDataBlock, $fileBytesRead)
                }

                # Save the file block to the Dataverse entitie's file attribute

                # Generate a new random blockId and add it to the list of blockIds
                $blockId = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.Guid]::NewGuid().ToString()))
                $blockIds.Add($blockId)

                # TODO : Use Web API Function => https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/uploadblock?view=dataverse-latest
                $uploadBlockRequest = [Microsoft.Crm.Sdk.Messages.UploadBlockRequest]@{
                    FileContinuationToken = $fileContinuationToken
                    BlockId = $blockId
                    BlockData = $fileDataBlock
                }

                # Upload a block: a failed block stops the upload (the commit would store a partial file)
                $uploadBlockResponse = $XrmClient | Invoke-XrmRequest -Request $uploadBlockRequest -ErrorAction Stop

                $fileBlockCounter = $fileBlockCounter + 1
            }
        }
        finally {
            # Finished reading from the file, or failed. Close the reader
            $fileReader.Close()
        }

        # Commit all file blocks
        # TODO : Use Web API Function => https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/commitfileblocksupload?view=dataverse-latest
        $commitBlocksUploadRequest = [Microsoft.Crm.Sdk.Messages.CommitFileBlocksUploadRequest]@{
            BlockList = $blockIds.ToArray()
            FileContinuationToken = $fileContinuationToken
            FileName = $fileName
            MimeType = $contentType
        }
        # The commit response holds the FileId and FileSizeInBytes of the stored file (B42)
        $XrmClient | Invoke-XrmRequest -Request $commitBlocksUploadRequest
    }
}

Export-ModuleMember -Function Update-XrmRecordFileUpload -Alias *;