Skip to main content
 首页 » 编程设计

powershell之将 Invoke-RestMethod 获得的流写入 PowerShell 中的图像文件

2024年06月20日74小虾米

我有一个 Asp.Net Web API,可以将图像流返回给客户端。

public HttpResponseMessage GetImage(string imageId) 
{ 
    ... 
    var response = new HttpResponseMessage(); 
    response.Content = new StreamContent(fileStream); 
    return response; 
} 

使用fiddler,可以看到图片下载成功。我想要实现的是使用PowerShell将其保存到本地镜像。

$result = Invoke-RestMethod ... 

我得到了$result,但不知道如何将其保存到本地磁盘,我尝试了以下方法:

# 1 
$result | Out-File ".../test.png" 
 
# 2: this exception said the $result is a string, cannot convert to Stream 
$fs = New-Object IO.FileStream "...\test.png","OpenOrCreate","Write" 
([System.IO.Stream]($result)).CopyTo($fs) 

使用 PowerShell 将图像保存到本地的正确方法是什么?

请您参考如下方法:

使用-OutFile开关:

$url = "http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=3c6263c3453b" 
Invoke-RestMethod $url -OutFile somefile.png 

您还可以使用 Invoke-WebRequest 代替 Invoke-RestMethod