我可以将 invoke-restmethod 的结果保存为变量而不是 powershell 中的 -outfile 吗?

Ull*_*okk 6 powershell

我有一个 Invoke-Restmethod API 脚本,它创建一个新的邮件列表并返回以下内容

  Code Message                              Result
  ---- -------                              ------                             
  1    Mailing list successfully created    12345678
Run Code Online (Sandbox Code Playgroud)

我需要结果(新邮件列表的 ID)以进行下一步操作。

我知道我可以使用 -outfile 将结果保存到 txt\xml\json 并使用 get-contents 导入它,但它让我觉得更高效、更干净,只需将结果保存在变量中,而无需保存输出文件并导入它回来了。有办法做到这一点吗?

我的完整代码:

Invoke-RestMethod $url -Method $method -Headers $headers -Body (ConvertTo-json $body) -ContentType "$outform"
Run Code Online (Sandbox Code Playgroud)

Ves*_*per 3

当然,是的。将-PassThruswitch 添加到您的Invoke-RestMethod调用中,并像平常一样将输出分配给变量。

$result = Invoke-RestMethod @args -PassThru # when there's "outfile" in args
Run Code Online (Sandbox Code Playgroud)

事实上,如果您使用-outfile,您的结果应该已经可以保存为变量。

$result = Invoke-RestMethod @args # when there's no "outfile" in args
Run Code Online (Sandbox Code Playgroud)

编辑:如果您只需要总结果中的一个字段(因此您不需要codemessage),则可以仅保存结果的result字段,如下所示:

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