Using PowerShell v3's Invoke-RestMethod to PUT/POST X Mb of a binary file

跟風遠走 提交于 2019-12-04 11:46:19

I believe the Invoke-RestMethod parameter you're looking for is

-TransferEncoding Chunked

but there is no control over the chunk or buffer size. Someone can correct me if I am wrong, but I think the chunk size is 4KB. Each chunk gets loaded into memory and then sent, so you memory doesn't fill up with the file you are sending.

To retrieve sections (chunks) of a file, you can create a System.IO.BinaryReader which has a handy dandy Read( [Byte[]] buffer, [int] offset, [int] length) method. Here's a function to make it easy:

function Read-Bytes {
    [CmdletBinding()]
    param (
          [Parameter(Mandatory = $true, Position = 0)]
          [string] $Path
        , [Parameter(Mandatory = $true, Position = 1)]
          [int] $Offset
        , [Parameter(Mandatory = $true, Position = 2)]
          [int] $Size
    )

    if (!(Test-Path -Path $Path)) {
        throw ('Could not locate file: {0}' -f $Path);
    }

    # Initialize a byte array to hold the buffer
    $Buffer = [Byte[]]@(0)*$Size;

    # Get a reference to the file
    $FileStream = (Get-Item -Path $Path).OpenRead();

    if ($Offset -lt $FileStream.Length) {
        $FileStream.Position = $Offset;
        Write-Debug -Message ('Set FileStream position to {0}' -f $Offset);
    }
    else {
        throw ('Failed to set $FileStream offset to {0}' -f $Offset);
    }

    $ReadResult = $FileStream.Read($Buffer, 0, $Size);
    $FileStream.Close();

    # Write buffer to PowerShell pipeline
    Write-Output -InputObject $Buffer;

}

Read-Bytes -Path C:\Windows\System32\KBDIT142.DLL -Size 10 -Offset 90;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!