Question:
If I use generic list like this:
1 2 3 4 5 |
$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’?
Answer:
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
1 2 |
[system.collections.generic.list[object]]$foo = , ( $foo | ? {$_.name -cnotmatch "^f" }) |
EDIT:
After some test I’ve found how use lambda expression using powershell scriptblock:
1 2 |
$foo.removeAll( { param($m) $m.name.startswith( 'F', $false , $null) }) |
This is the right way for using method that needs System.Predicate
in powershell