如何在PowerShell中将HTTP PUT上载到VMware ESX Server?

时间:2008-09-15 19:14:57

标签: http powershell vmware esx

从版本3.5开始,VMware ESX,ESXi和VirtualCenter应该能够支持HTTP PUT上传。我知道如何进行下载,这很容易。我以前从未做过PUT。

有关该主题的背景信息如下:http://communities.vmware.com/thread/117504

2 个答案:

答案 0 :(得分:4)

您应该查看PoshCode cmdlet脚本模块中的Send-PoshCode函数...它使用的是POST,而不是PUT,但该技术实际上是相同的。我没有PUT服务器我可以考虑测试,但基本上,设置你的$ url和你的$ data,并做类似的事情:

param($url,$data,$filename,[switch]$quiet)

$request = [System.Net.WebRequest]::Create($url)
$data = [Text.Encoding]::UTF8.GetBytes( $data )

## Be careful to set your content type appropriately...
## This is what you're going to SEND THEM
$request.ContentType = 'text/xml;charset="utf-8"' # "application/json"; # "application/x-www-form-urlencoded"; 
## This is what you expect back
$request.Accept = "text/xml" # "application/json";

$request.ContentLength = $data.Length
$request.Method = "PUT"
## If you need Credentials ...
# $request.Credentials = (Get-Credential).GetNetworkCredential()

$put = new-object IO.StreamWriter $request.GetRequestStream()
$put.Write($data,0,$data.Length)
$put.Flush()
$put.Close()

## This is the "simple" way ...
# $reader = new-object IO.StreamReader $request.GetResponse().GetResponseStream() ##,[Text.Encoding]::UTF8
# write-output $reader.ReadToEnd()
# $reader.Close()

## But there's code in PoshCode.psm1 for doing a progress bar, something like ....

$res = $request.GetResponse();
if($res.StatusCode -eq 200) {
   [int]$goal = $res.ContentLength
   $reader = $res.GetResponseStream()
   if($fileName) {
      $writer = new-object System.IO.FileStream $fileName, "Create"
   }

   [byte[]]$buffer = new-object byte[] 4096
   [int]$total = [int]$count = 0
   do
   {
      $count = $reader.Read($buffer, 0, $buffer.Length);
      if($fileName) {
         $writer.Write($buffer, 0, $count);
      } else {
         $output += $encoding.GetString($buffer,0,$count)
      }
      if(!$quiet) {
         $total += $count
         if($goal -gt 0) {
            Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100)
         } else {
            Write-Progress "Downloading $url" "Saving $total bytes..." -id 0
         }
      }
   } while ($count -gt 0)

   $reader.Close()
   if($fileName) {
       $writer.Flush()
       $writer.Close()
   } else {
       $output
   }
}
$res.Close();

答案 1 :(得分:2)

VI Toolkit Extensions中使用Copy-TkeDatastoreFile。它将与二进制文件一起使用。