PowerShell: how to capture (or suppress) write-host

后端 未结 3 1990
清酒与你
清酒与你 2021-01-20 00:37

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

3条回答
  •  情话喂你
    2021-01-20 01:00

    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.

提交回复
热议问题