I have a script call \"a.ps1\":
write-host \"hello host\"
\"output object\"
I want to call the script and obtain the output object, but I a
There really is no easy way to do this.
A workaround is to override the default behavior of Write-Host by defining a function with the same name:
function global:Write-Host() {}
This is very flexible. And it works for my simplistic example above. However, for some unknown reason, it doesn't work for the real case where I wanted to apply (maybe because the called script is signed and for security reasons it doesn't allow caller to arbitrarily change the behavior).
Another way I tried was to modify the underlying Console's stdout by:
$stringWriter = New-Object System.IO.StringWriter
[System.Console]::SetOut($stringWriter)
[System.Console]::WriteLine("HI") # Outputs to $stringWriter
Write-Host("HI") # STILL OUTPUTS TO HOST :(
But as you can see, it still doesn't work.