Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to RemoveAll when using generic list<T> in powershell

If I use generic list like this:

$foo = New-Object 'system.collections.generic.list[object]'
$foo.Add((New-Object PSObject -Property @{ Name="Foo1"; }))
$foo.Add((New-Object PSObject -Property @{ Name="Foo2"; }))
$foo.Add((New-Object PSObject -Property @{ Name="foo3"; }))

How can I apply RemoveAll() method of List<T>? Is it possible to use predicates? How can I for example remove all items that start with capital 'F'?

like image 623
iLemming Avatar asked May 08 '12 17:05

iLemming


1 Answers

I think the only way is without using System.Predicate that needs delegates (sorry, but really I can't figure out how create anonymous delegates in powershell) and use the where-object clause.

In my example I re-assign the result to same $foo variable that need to be cast again to list<T>.

To avoid error if result count is only one it need the ',' to create always an array value

[system.collections.generic.list[object]]$foo =  , ( $foo | ? {$_.name  -cnotmatch "^f" })

EDIT:

After some test I've found how use lambda expression using powershell scriptblock:

$foo.removeAll( { param($m)  $m.name.startswith( 'F', $false , $null)  })

This is the right way for using method that needs System.Predicate in powershell

like image 80
CB. Avatar answered Nov 16 '22 04:11

CB.