如何从阵列中删除 powershell

Man*_*ndy 2 powershell powershell-3.0

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

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

$a = $a | where {condition to remove lines}
Run Code Online (Sandbox Code Playgroud)

出现以下错误

Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
Run Code Online (Sandbox Code Playgroud)

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

mkl*_*nt0 5

鉴于问题的通用标题,让我提出一些一般性观点:

  • 数组(在 .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 })
Run Code Online (Sandbox Code Playgroud)

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

但是,由于 PowerShell 自动解包元素结果,因此您需要@(...),数组子表达式运算符来确保即使只返回单个元素,$a它仍然是一个数组- 另一种方法是将变量类型约束为数组:

[array] $a = $a | Where-Object { $_ -ne 2 }
Run Code Online (Sandbox Code Playgroud)

请注意,即使结果被分配回输入变量$a$a现在技术上包含一个数组(旧数组,如果没有在其他地方引用,最终将被垃圾收集)。


至于你尝试过的

如何从数组中删除 pscustomobject 行

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

+当您尝试将运算符与实例一起使用[pscustomobject]作为 LHS 时,会出现此错误消息,但不支持该操作;例如:

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

PowerShell 不知道如何向自定义对象“添加”某些内容,因此它会抱怨。