rest - 使用PassThru时Invoke-RestMethod OutFile为空

标签 rest powershell output cmdlet

使用PowerShell 4.0和Invoke-RestMethod cmdlet。我在使用-OutFile和-PassThru选项时遇到麻烦。 每当我添加-PassThru选项时,都会创建-OutFile,但内容为空!

根据Invoke-RestMethod Documentation,当这些选项一起使用时,输出文件和管道对象都应该可用。 “-OutFile将响应主体保存在指定的输出文件中。[...]要将结果发送到文件和管道,请使用Passthru参数。

这是一个测试,用于重复出现的问题。在这里,我正在调用rest api,尝试同时保存对文件的响应并反序列化为powershell对象。

"POWERSHELL VERSION $($host.Version.ToString())"
$date = Invoke-RestMethod "http://date.jsontest.com" -OutFile "OutFile.txt" -PassThru
Get-Content "OutFile.txt"
# FILE IS EMPTY!!! PASSTHRU SEEMS TO RESULT IN EMPTY FILE
$date
# powershell object has the date received from api

这是两个在没有PassThru选项的情况下验证Invoke-RestMethod正常功能的测试
# ... Test # 1, call rest api and deserialize into powershell object
$date = Invoke-RestMethod "http://date.jsontest.com"
$date
# Output shows the date retrieved from sample restful service
# ... Test # 2, call rest api and save response body directly to a file
Invoke-RestMethod "http://date.jsontest.com" -OutFile "OutFile.txt"
Get-Content "OutFile.txt"
# Output shows contents of rest api response body (json text)

我认为这些测试应该可以帮助其他人看到我遇到的麻烦。我的问题是,是否缺少来使它起作用,或者这可能是cmdlet的错误? 我已经用Google搜索了一些解决方案,但没有关于此问题的明显报告。我想将-OutFile用作与内容编码有关的另一个Invoke-RestMethod问题的解决方法的一部分,如Bug? Invoke-RestMethod and UTF-8 data所述。 -PassThru选项对我查看返回的数据并终止多请求(分页)odata结果集上的迭代很有帮助。

最佳答案

我相信-PassThru开关仅将所有输出重定向到控制台,并且我认为这就是为什么文件为空的原因。但是,由于您拥有一个变量,因此您可以像这样再添加一行。 。 。

Write-Output -InputObject $date | Out-File -FilePath "OutFile.txt"

关于rest - 使用PassThru时Invoke-RestMethod OutFile为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43009359/

相关文章:

rest - 使用Restful-API插件上传Grails文件

javascript - 如何实现使用 API 获取信息的搜索栏

http - RESTfully 设计/登录或/注册资源?

powershell - 禁止来自非PowerShell命令的输出?

powershell - Powershell中的值(value)没有增长

c - 从txt文件中获取变量

python - 如何每行打印几个数组元素到文本文件

java - 如何从curl获取REST Web服务中的参数?

windows - 如何在具有管理员权限的 Windows 任务计划程序中设置 Powershell 脚本?

android - Android eclipse中用zxing处理数据输出二维码