I have the following code inside a PowerShell function:
$client.List($target, {
param ($sender, $e)
Write-Host "Here it is: $e"
Write-Output $e
})
(client is a SharpSvn.SvnClient, and $target is some repository URL)
When I run it (just calling my function in console), I get a list of "Here it is: SharpSvn.SvnListEventArgs" for each of the item in repository, so I know the callback is executed.
However actual items are not put into the output (either pipeline or console).
If I put Write-Output outside the callback, the item is processed correctly, so I assume it has something with being in a callback block.
How do I make callback block process Write-Output correctly?
What's happening is that the ScriptBlock is getting converted into a delegate (EventHandler<SvnListEventArgs>) which returns void so Write-Output doesn't have anywhere to send the output. It's a bit like this:
[Action]$action = { Write-Host "Test"; Write-Output "Test" }
$action.Invoke()
Since Action doesn't return anything there is no where for the result of Write-Output to go. Now if the delegate returned an object it would work:
[Func[object]]$func = { Write-Host "Test"; Write-Output "Test"; Write-Output "Test2" }
$func.Invoke()
I guessing the way Write-Output works under the hood is that it sends the output somewhere which will cause all the outputs to be returned, if possible, when execution exits the script block. It doesn't have a reference the "current pipeline" or "currently executing function", so it can't write there directly.
I think the way to go about capturing the output is to do something like this:
$list = new-object System.Collections.Generic.List[Object]
$client.List($target, {
param ($sender, $e)
Write-Host "Here it is: $e"
$list.Add($e)
})
Write-Output $list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With