如何从循环中的 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 的基础)是固定大小数据结构。因此,您无法直接删除其中的元素。
但是,您可以创建一个新数组,该数组是原始数组的副本,其中包含不需要的元素省略,这就是管道方法所促进的:
# 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 自动解包一个单元素结果,因此您需要 @(...)
,即 array-subexpression operator确保即使只返回单个元素,$a
仍然是一个数组 - 另一种方法是将变量类型约束作为数组:
[array] $a = $a | Where-Object { $_ -ne 2 }
请注意,即使结果被分配回输入变量 $a
,$a
现在在技术上包含一个 new 数组(并且旧的,如果没有在其他地方引用,最终将被垃圾收集)。
至于你尝试过的:
How can i delete row from array which is pscustomobject
如wOxxOm指出,[pscustomobject]
不是数组,但也许您的意思是说您有一个数组,其元素是自定义对象,在这种情况下,适用上述方法。< br/>
或者,如果要从中删除元素的数组存储在自定义对象的属性中,请改为通过管道发送该属性的值,并将结果分配回该属性。
当您尝试将 +
运算符与 [pscustomobject]
实例一起使用作为 LHS 时,会出现此错误消息,但该操作不受支持;例如:
PS> ([pscustomobject] @{ foo = 'bar' }) + 1
Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
...
PowerShell 不知道如何向自定义对象“添加”某些内容,因此它会提示。
关于powershell - 如何从阵列中删除 powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44468606/