powershellrest

Powershell 7 fails when uploading a file with Invoke-RestMethod for multipart form but works in Powershell 5


I am uploading files to a resource using REST in the following way.

    #File names
    $PathToFile = "C:\Path to file here.zip"
    $PackageName = $(Split-Path $PathToFile -Leaf)

    #Byte stream and encoding
    $PackageByteStream = [System.IO.File]::ReadAllBytes("$PathToFile")
    $Encoding = [System.Text.Encoding]::GetEncoding("ISO-8859-1")
    $FileEncoding = $Encoding.GetString($PackageByteStream)

    #Create the content body
    $Boundary = (New-Guid).ToString()
    $ContentBody = "--$Boundary
Content-Disposition: form-data; name=""files""; filename=""$PackageName""
Content-Type: application/octet-stream

$FileEncoding
--$Boundary--
"

    #Parameter Object
    $Parameters = @{
        Uri                   = "http://myUrlhere.com/TargetResource"
        Method                = "Post"
        UseDefaultCredentials = $true
        ContentType           = "multipart/form-data; boundary=`"$Boundary`""
        Body                  = $ContentBody
    }
    if ($IsCoreCLR -and ($Parameters.Uri -match '^http:')) {
        $Parameters += @{ "AllowUnencryptedAuthentication" = $true }
    }

    #Upload the file
    Invoke-RestMethod @Parameters

This works in Powershell 5.1 but in Powershell 7 it fails with "Offset to Central Directory cannot be held in an Int64". The only related post I could find on that was someone who used ReadAllText instead of ReadAllBytes, but since I already use ReadAllBytes I don't think it's that.

Is there something that has changed between Powershell versions that would cause this behaviour?


Solution

  • I presume you've run into the following:

    In other words, in the context of your splatted arguments:

    # ...
    
    $Parameters = @{
      Uri    = "http://myUrlhere.com/TargetResource"
      Method = "Post"
      UseDefaultCredentials = $true
      ContentType = "multipart/form-data; boundary=`"$Boundary`"; charset=iso-8859-1"
      Body = $ContentBody
    }
    
    # ...
    
    Invoke-RestMethod @Parameters
    

    Taking a step back: