将流从Invoke-RestMethod写入PowerShell中的映像文件

Jer*_*ian 3 powershell stream

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

public HttpResponseMessage GetImage(string imageId)
{
    ...
    var response = new HttpResponseMessage();
    response.Content = new StreamContent(fileStream);
    return response;
}
Run Code Online (Sandbox Code Playgroud)

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

$result = Invoke-RestMethod ...
Run Code Online (Sandbox Code Playgroud)

我得到了$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)
Run Code Online (Sandbox Code Playgroud)

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

Raf*_*Raf 7

使用-OutFile开关:

$url = "http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=3c6263c3453b"
Invoke-RestMethod $url -OutFile somefile.png
Run Code Online (Sandbox Code Playgroud)

您也可以使用Invoke-WebRequest而不是Invoke-RestMethod.