Author Posts

November 6, 2013 at 12:51 pm

i have array :

Clear-Host;
$arr=@();
Add-Type @'
public class MyObject2
{
public int MyField = 5;
public void xTimesMyField(int x) {
MyField=x;
}
}
'@
for( $i=1;$i -le 10;++$i){
$object = New-Object MyObject2;
$object.xTimesMyField($i);
$arr+=$object;
}
$arr

how can i remove one of the elements of the array by theMyField property when it equales to certain value?

November 6, 2013 at 12:53 pm

You can't remove elements from a .NET Array object. You can either use another type of collection (such as an ArrayList), or you can filter the elements and assign them to a new array object (even if it's in the same variable.) For example:

$arr = $arr | Where-Object { $_.MyField -ne 'SomeValue' }

November 8, 2013 at 12:28 pm

You can do some funky stuff with multiple assignment and recursion to remove an element.

Removing based on what the element is.

`
function remove-item-list ($item,[array]$chckd_list=@(),[array]$list=(throw"the item $item was not in the list"))
{ if ($list.length -lt 1 ) { throw "the item $item was not in the list" }

   $check_item,$temp_list=$list
   if ($check_item -eq $item ) {
      $chckd_list+=$temp_list
      return $chckd_list }
   else {
      $chckd_list+=$check_item
      return (remove-item-list -item $item -chckd_list $chckd_list -list $temp_list )}
}
`

Removing based on index number.

`
function remove-index-list ([int]$count=0,[int]$index,[array]$chckd_list=@(),[array]$list)
{if (($list.length+$count-1) -lt $index ) { throw "the index is out of range" }
    $check_item,$temp_list=$list
    if ($count -eq $index) {
       $chckd_list+=$temp_list
       return $chckd_list}
    else {
       $chckd_list+=$check_item
       return (remove-index-list -count ($count + 1) -index $index -chckd_list $chckd_list -list $temp_list )}

}
`