首页 > 解决方案 > 我可以使用 Invoke-WebRequest 将二进制数据写入文件并仍然获得状态码吗?

问题描述

我需要使用 POST 请求下载文件,但是,由于 PowerShell 似乎无法处理管道和变量中的二进制数据(Out-File不支持二进制数据),我需要-OutFile使用Invoke-WebRequest. 但是,这样做时,它不再输出状态代码,以便我可以在变量中捕获它:

PS K:\hmpf> $Filepath = "E:\shmimpf\g\yyv.fgr"
PS K:\hmpf> $URL = "https://wwwh.ipswich.org/tycobrahe/magazine.php?burgerflipcount=76"
PS K:\hmpf> (Invoke-WebRequest -Uri $URL -OutFile $Filepath -Method Post).StatusCode
PS K:\hmpf> (Invoke-WebRequest -Uri $URL -Method Post).StatusCode
200
PS K:\hmpf>

标签: powershelldownload

解决方案


文档中Invoke-WebRequest

-PassThru

    Indicates that the cmdlet returns the results, in addition to writing them to a file. 
    This parameter is valid only when the OutFile parameter is also used in the command.

因此,要结合以下内容获得响应结果-OutFile

(Invoke-WebRequest -Uri $URL -OutFile $Filepath -Method Post -PassThru).StatusCode

推荐阅读