如何从数组Powershell中删除

How to Delete from array powershell

如何从循环中 pscustomobject 的数组中删除行?

如果我在循环中使用它会出现错误:

$a = $a | where {condition to remove lines}

出现以下错误

Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.

关于从数组中删除行的任何建议。

考虑到问题的通用标题,让我提出一些一般性观点:

  • 数组(在 .NET 中,它是 PowerShell 的基础)是 fixed-size 数据结构。因此,您不能从中直接删除元素

  • 但是,您可以创建一个数组,它是一个复制 不需要的元素 省略了 ,这就是管道方法所促进的:

# Sample array.
$a = 1, 2, 3

# "Delete" element 2 from the array, which yields @(1, 3).
# @(...) ensures that the result is treated as an array even if only 1 element is returned.
$a = @($a | Where-Object { $_ -ne 2 })

当您将其分配给变量时,PowerShell 会自动捕获 数组(类型 [System.Object[]])中管道的输出。

但是,由于 PowerShell 自动 解包 一个 single-element 结果,您需要 @(...)array-subexpression operator 以确保 $a 仍然是 array 即使只返回一个元素 - 替代方法是 type-constrain 作为数组的变量:

[array] $a = $a | Where-Object { $_ -ne 2 }

请注意,即使结果被分配回输入变量 $a$a 现在在技术上包含一个 new 数组(和旧数组,如果它没有在别处被引用,最终将是 garbage-collected).


至于你试过的

How can i delete row from array which is pscustomobject

正如 wOxxOm 指出的那样,[pscustomobject] 不是数组,但也许你的意思是说你有一个数组,其 元素 是自定义的 objects,在这种情况下,上述方法适用。
或者,如果要从中删除元素的数组存储在自定义 object 的 属性 中,则通过管道发送 属性 的值相反,并将结果分配回 属性.

当您尝试将 + 运算符与 [pscustomobject] 实例一起用作 LHS 时出现错误消息,这是不支持的;例如:

PS> ([pscustomobject] @{ foo = 'bar' }) + 1
Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
...

PowerShell 不知道如何向自定义 object“添加”某些内容,所以它会抱怨。