PowerShell:如何捕获(或抑制)写主机 [英] PowerShell: how to capture (or suppress) write-host
问题描述
我有一个脚本调用a.ps1":
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 also want the standard output to be suppressed:
$result = .\a.ps1
# Don't want anything printed to the console here
有什么提示吗?
推荐答案
确实没有简单的方法可以做到这一点.
There really is no easy way to do this.
一种解决方法是通过定义一个同名的函数来覆盖 Write-Host 的默认行为:
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.
这篇关于PowerShell:如何捕获(或抑制)写主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!