【问题标题】:Using PowerShell v3's Invoke-RestMethod to PUT/POST X Mb of a binary file使用 PowerShell v3 的 Invoke-RestMethod PUT/POST X Mb 的二进制文件
【发布时间】:2012-02-26 17:04:38
【问题描述】:

我一直在使用 PowerShell v3(来自here 的 CTP2)及其新的 Invoke-RestMethod 做一些工作,如下所示:

Invoke-RestMethod -Uri $dest -method PUT -Credential $cred -InFile $file

但是,我想用它来推送 very 个大型二进制对象,因此希望能够从大型二进制文件推送 range 字节。

例如,如果我有一个 20Gb VHD,我想将其分成多个块,例如,每个 5Gb(不先拆分和保存单个块),然后将它们 PUT/POST 到 BLOB 存储,如 S3、Rackspace、 Azure 等。我还假设块大小大于可用内存。

我读过 Get-Content 在处理大型二进制文件时效率不高,但这似乎不是一个晦涩难懂的要求。有没有人有任何可以用于此的方法,特别是与 PowerShell 的新 Invoke-RestMethod 结合使用?

【问题讨论】:

    标签: powershell powershell-3.0


    【解决方案1】:

    我相信您正在寻找的 Invoke-RestMethod 参数是

    -TransferEncoding Chunked
    

    但无法控制块或缓冲区大小。如果我错了,有人可以纠正我,但我认为块大小是 4KB。每个块都被加载到内存中然后发送,因此您的内存不会被您发送的文件填满。

    【讨论】:

      【解决方案2】:

      要检索文件的部分(块),您可以创建一个System.IO.BinaryReader,它有一个方便的Read( [Byte[]] buffer, [int] offset, [int] length) 方法。这是一个让它变得简单的函数:

      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;
      

      【讨论】:

      • 看起来很方便。你能给我一个例子,将它与invoke-restmethod结合起来,将X Gb的特定文件发布到一个url,而不先将它加载到内存中(也许使用@JakeRobinson下面的方法)?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多