gpt4 book ai didi

arrays - 为什么 PowerShell 将 `Where` 谓词应用于空列表

转载 作者:行者123 更新时间:2023-12-02 14:06:16 24 4
gpt4 key购买 nike

如果我在 PowerShell 中运行此命令,我希望看到输出 0 (零):

Set-StrictMode -Version Latest

$x = "[]" | ConvertFrom-Json | Where { $_.name -eq "Baz" }
Write-Host $x.Count

相反,我收到此错误:

The property 'name' cannot be found on this object. Verify that the     property exists and can be set.
At line:1 char:44
+ $x = "[]" | ConvertFrom-Json | Where { $_.name -eq "Baz" }
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException

如果我在 "[]" | ConvertFrom-Json 周围加上大括号就变成这样了:

$y = ("[]" | ConvertFrom-Json) | Where { $_.name -eq "Baz" }
Write-Host $y.Count

然后它就“起作用了”。

引入括号之前有什么问题?

解释“works”周围的引号 - 设置严格模式 Set-StrictMode -Version Latest表示我调用.Count$null上目的。通过包裹 @() 可以解决这个问题:

$z = @(("[]" | ConvertFrom-Json) | Where { $_.name -eq "Baz" })
Write-Host $z.Count

我觉得这很令人不满意,但这是实际问题的旁白。

最佳答案

Why is PowerShell applying the predicate of a Where to an empty list?

因为 ConvertFrom-Json 告诉 Where-Object 不要尝试枚举其输出。

因此,PowerShell 尝试访问空数组本身的 name 属性,就像我们这样做:

$emptyArray = New-Object object[] 0
$emptyArray.name

当您将 ConvertFrom-Json 括在括号中时,powershell 会将其解释为一个单独管道,该管道在发送任何输出之前执行并结束到 Where-Object,因此 Where-Object 无法知道 ConvertFrom-Json 希望它如此对待数组。

<小时/>

我们可以通过使用 -NoEnumerate 开关参数集显式调用 Write-Output 来在 powershell 中重新创建此行为:

# create a function that outputs an empty array with -NoEnumerate
function Convert-Stuff
{
Write-Output @() -NoEnumerate
}

# Invoke with `Where-Object` as the downstream cmdlet in its pipeline
Convert-Stuff | Where-Object {
# this fails
$_.nonexistingproperty = 'fail'
}

# Invoke in separate pipeline, pass result to `Where-Object` subsequently
$stuff = Convert-Stuff
$stuff | Where-Object {
# nothing happens
$_.nonexistingproperty = 'meh'
}

Write-Output -NoEnumerate 内部调用 Cmdlet.WriteObject(arg, false),这又导致运行时枚举针对下游 cmdlet 进行参数绑定(bind)期间的 arg 值(在您的情况下 Where-Object)

<小时/>

Why would this be desireable?

在解析 JSON 的特定上下文中,这种行为可能确实是可取的:

$data = '[]', '[]', '[]', '[]' |ConvertFrom-Json

既然我向它传递了 5 个有效的 JSON 文档,那么我不应该期望从 ConvertFrom-Json 中得到正好 5 个对象吗? :-)

关于arrays - 为什么 PowerShell 将 `Where` 谓词应用于空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55575501/

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