PrivateFunctions/Upload-SmallFileToOneDrive.ps1

<#
.SYNOPSIS
    This function uploads a small file up to 4MB in size to OneDrive.
.DESCRIPTION
    This function uploads a small file up to 4MB in size to OneDrive.
    It makes use of the OneDrive "Upload Small Files" REST endpoint:
    https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_put_content?view=odsp-graph-online
#>

function Upload-SmallFileToOneDrive {
    [CmdletBinding(PositionalBinding=$false)]
    [OutputType([Bool])]
    param (
        # The path to the file on the local machine.
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$filePath,

        # The path of the destination file in OneDrive.
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$destinationFilePath,

        # The User Principal Name of the user whose OneDrive account will receive the file.
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$userPrincipalName,

        # The Microsoft Graph authentication token.
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$token,

        # Select the stream where the messages will be directed.
        [Parameter(Mandatory=$false)]
        [ValidateSet("Information", "Warning", "Error")]
        [String]$outputStream = "Error"
    )

    # Convert the file into a string
    $fileInBytes = [System.IO.File]::ReadAllBytes($filePath)
    $fileInString = [String]::New($fileInBytes, 0, $fileInBytes.Length)

    # Upload the file to OneDrive
    Write-Information "Uploading the file '$($filePath)' to OneDrive."
    try {
        $invokeRestMethodParams = @{
            Uri     = "https://graph.microsoft.com/v1.0/users/$($userPrincipalName)/drive/root:/$($destinationFilePath):/content"
            Method  = "PUT"
            Headers = @{
                Accept         = "application/json"
                "Content-Type" = "text/plain"
                Authorization  = "bearer $($token)"
            }
            Body    = $fileInString
        }
        $response = Invoke-RestMethod @invokeRestMethodParams
        if (!$response -or [String]::IsNullOrWhiteSpace($response.id)) {
            Write-OutputMessage "Failed to upload the file '$($filePath)' to OneDrive." -OutputStream $outputStream -ReturnMessage:$false
            return $false
        }
    }
    catch {
        Write-OutputMessage "Exception occurred while uploading the file '$($filePath)' to OneDrive.`r`n$($_.Exception.Message)" -OutputStream $outputStream -ReturnMessage:$false
        return $false
    }

    # Successfully uploaded the file
    return $true
}