我需要使用 POST 请求下载文件,但是,由于 PowerShell 似乎无法处理管道和变量中的二进制数据(Out-File
不支持二进制数据),我需要使用 Invoke-WebRequest
的 -OutFile
参数。但是,在执行此操作时,它不再输出状态代码,因此我可以将其捕获到变量中:
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>
最佳答案
来自documentation for 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
关于powershell - 我可以使用 Invoke-WebRequest 将二进制数据写入文件并仍然获取状态代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61233166/