gpt4 book ai didi

powershell - `Invoke-RestMethod -Uri “…”-方法获取|选择X,Y ` doesn' t时返回任何行,而`(Invoke-RestMethod -Uri “…”-方法Get)|选择X,Y`吗?

转载 作者:行者123 更新时间:2023-12-02 23:51:29 26 4
gpt4 key购买 nike

我有一个REST API,它将返回行。然而,

为什么Invoke-RestMethod -Uri "..." -Method Get | select XXX,YYY仅返回 header ?

XXX YYY
--- ---

但是 (Invoke-RestMethod -Uri "..." -Method Get) | select X,Y返回行?

首先分配一个变量也可以。
$x = Invoke-RestMethod -Uri "..." -Method Get | select XXX,YYY
$x | select xxx,yyyy

最佳答案

一般来说:

  • 如果命令将集合作为单个对象输出,则Select-Object X, Y将无法按预期的方式工作,因为它将在集合对象上查找无法找到它们的那些属性,在这种情况下,Select-Object将使用所请求的属性,然后所有这些属性都包含$null
  • Invoke-RestMethod可能是此行为的候选者,因为它可能会通过 ConvertFrom-Json 隐式地将返回值解析为JSON,实际上会将数组作为单个对象输出;在this GitHub issue中讨论了这种令人惊讶的行为。
  • 在命令周围放置(...)会强制枚举,这样可以解决问题:
  • # Place (...) around the Invoke-RestMethod call to force enumeration.
    (Invoke-RestMethod -Uri "..." -Method Get) | select XXX,YY

    另一个选项是分配给(中间)变量,如您的问题所示-尽管 (...)方法更简单,但是如果您实际上不需要存储中间结果。
    # Store array in a variable.
    $array = Invoke-RestMethod -Uri "..." -Method Get

    # An array stored in a variable sent through the pipeline is
    # invariably enumerated.
    $array | select X,Y

    之所以可行,是因为通过管道发送存储在变量中的数组总是会枚举它(将元素逐个发送)。

    通过分配给变量,您可以有效地消除一个命令一个输出一个N对象和一个将N元素数组作为单个对象输出的命令之间的区别:
    # Send an array *as a whole* through the pipeline.
    PS> (Write-Output -NoEnumerate (1..3) | Measure-Object).Count
    1 # That is, the 3-element array was sent as *one* object

    # Wrapping the command in (...) forces enumeration.
    PS> ((Write-Output -NoEnumerate (1..3)) | Measure-Object).Count
    3 # elements were sent *one by one*

    # Store output-as-a-whole array in a variable,
    # then send the variable through the pipeline -
    # which also forces enumeration.
    PS> $array = Write-Output -NoEnumerate (1..3); ($array | Measure-Object).Count
    3 # elements were sent *one by one*

    相反,如果确实希望通过管道发送存储在变量中的数组作为整体, ,则有两个选择:
    $array = 1..3

    # Use Write-Output -NoEnumerate:
    PS> (Write-Output -NoEnumerate $array | Measure-Object).Count
    1 # array was sent *as a whole*

    # Alternatively - faster and more concise, but more obscure -
    # wrap the array in an aux. wrapper array, so that only
    # the wrapper array is enumerated, sending the original array
    # as a whole:
    PS> (, $array | Measure-Object).Count
    1 # array was sent *as a whole*

    关于powershell - `Invoke-RestMethod -Uri “…”-方法获取|选择X,Y ` doesn' t时返回任何行,而`(Invoke-RestMethod -Uri “…”-方法Get)|选择X,Y`吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209879/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com