Mandy
Mandy

Reputation: 33

How to Delete from array powershell

How can i delete row from array which is pscustomobject in a loop?

Getting errors if i use this in the loop:

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

Getting the below error

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

any suggetion to remove row from array.

Upvotes: 2

Views: 9128

Answers (1)

mklement0
mklement0

Reputation: 440546

Let me make some general points, given the generic title of the question:

  • Arrays (in .NET, which underlies PowerShell) are fixed-size data structures. As such, you cannot delete elements from them directly.

  • However, you can create a new array that is a copy of the original one with the unwanted elements omitted, and that is what the pipeline approach facilitates:

# 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 automatically captures the output from a pipeline in an array (of type [System.Object[]]) when you assign it to a variable.

However, since PowerShell automatically unwraps a single-element result, you need @(...), the array-subexpression operator to ensure that $a remains an array even if only a single element was returned - the alternative would be to type-constrain the variable as an array:

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

Note that even though the result is assigned back to input variable $a, $a now technically contains a new array (and the old one, if it is not being referenced elsewhere, will eventually be garbage-collected).


As for what you tried:

How can i delete row from array which is pscustomobject

As wOxxOm points out, [pscustomobject] are not arrays, but perhaps you meant to say that you have an array whose elements are custom objects, in which case the above approach applies.
Alternatively, if the array to delete elements from is stored in a property of a custom object, send that property's value through the pipeline instead, and assign the results back to that property.

The error message occurs when you try to use the + operator with a [pscustomobject] instance as the LHS, which is not supported; e.g.:

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

PowerShell doesn't know how to "add" something to a custom object, so it complains.

Upvotes: 5

Related Questions