0

Given a simple generic list of strings like this

$log = [System.Collections.Generic.List[String]]::new()
$log.Add('?_Label')
$log.Add('=_Item')

I can replace prefixes with something like this

$log | Foreach-Object {$_ -replace '^\?_', 'E_'}

But I would like to understand how to do this with the .ForEach() method rather than the pipeline. I have tried

$log.ForEach({$_ -replace '^\?_', 'E_' })
$log.ForEach({$arg -replace '^\?_', 'E_' })
$log.ForEach({param([String] $item) $item -replace '^\?_', 'E_' })

and none works. I know from this that I need a delegate, and this in theory should tell me how to do it. But I am at a loss. I also found this which is what sent me down the initial rabbit hole, but this is obviously a native PowerShell .ForEach() method, where $_ is valid, and I am dealing with a native .NET method, where $_ does not apply. But I think there is even more that I am missing.

Gordon
  • 6,257
  • 6
  • 36
  • 89
  • 1
    The one with `param (...)` should work (or just using `$args[0]`), but keep in mind that the ForEach method is only for side effects; it doesn't return anything. – jkiiski Dec 05 '22 at 13:04
  • 2
    `List` `.ForEach` method is not the same as the intrinsic `.ForEach` method – Santiago Squarzon Dec 05 '22 at 13:13
  • @jkiiski Ugh. I could have sworn there was a way to return something too. – Gordon Dec 05 '22 at 13:32
  • 1
    You might simply do: `$log -replace '^\?_', 'E_'` – iRon Dec 05 '22 at 13:41
  • @iRon, that does the trick. I just need to cast back to List and I am off to the races. `$log = [System.Collections.Generic.List[String]]($log -replace '^\?_', 'E_')` – Gordon Dec 05 '22 at 14:08

1 Answers1

1

You can create new delegate using [System.Action[type]]$actionName syntax

[System.Action[String]]$action = {param($item) Write-Host ($item -replace '\?_', 'E_') }

and pass this Action $action to ForEach method.

$log.ForEach($action)
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
  • Hey, I have an off topic question. Would this apply to the answer posted [here](https://stackoverflow.com/a/32364847/14903754)? Seeing as `[System.Threading.Tasks.Parallel]::ForEach()` doesn't know about runspaces? – Abraham Zinala Dec 05 '22 at 19:27