PowerShell:如何捕获(或抑制)写主机

时间:2013-01-23 01:18:41

标签: powershell

我有一个脚本调用“a.ps1”:

write-host "hello host"
"output object"

我想调用脚本并获取输出对象,但我也希望抑制标准输出:

$result = .\a.ps1
# Don't want anything printed to the console here

任何提示?

3 个答案:

答案 0 :(得分:4)

真的没有简单的方法可以做到这一点。

解决方法是通过定义具有相同名称的函数来覆盖Write-Host的默认行为:

function global:Write-Host() {}

这非常灵活。它适用于我上面简单的例子。但是,由于某些未知原因,它不适用于我想要应用的实际情况(可能因为被调用的脚本已签名,出于安全原因,它不允许调用者任意改变行为)。

我尝试的另一种方法是通过以下方式修改底层Console的标准输出:

$stringWriter = New-Object System.IO.StringWriter
[System.Console]::SetOut($stringWriter)
[System.Console]::WriteLine("HI") # Outputs to $stringWriter
Write-Host("HI") # STILL OUTPUTS TO HOST :(

但正如你所看到的,它仍然不起作用。

答案 1 :(得分:0)

输出对象即"output object“输出到standard output。所以我不认为你想要抑制标准输出。如果你不想在控制台上打印任何东西就不要使用Write-Host因为它绕过所有流(stdout,stderr,warning,verbose,debug)并直接显示给主机。目前还没有我想知道的重定向主机输出的简单机制。

BTW为什么你不想在以后看到它时显示“hello host”到控制台?

答案 2 :(得分:0)

好的,我做了一点挖掘。您可以使用:

The Following Link

并做:

$result = .\1.ps1 | Select-WriteHost -Quiet
$result[1]

然后在变量中选择第二个对象:

Another explanation

您还可以以不会将Write-Host更改为Write-Output的方式更改脚本,只需“删除”Write-Host。

完成...

function Remove-WriteHost
{
   [CmdletBinding(DefaultParameterSetName = 'FromPipeline')]
   param(
     [Parameter(ValueFromPipeline = $true, ParameterSetName = 'FromPipeline')]
     [object] $InputObject,

     [Parameter(Mandatory = $true, ParameterSetName = 'FromScriptblock', Position = 0)]
     [ScriptBlock] $ScriptBlock
   )

   begin
   {
     function Cleanup
     {
       # Clear out our proxy version of Write-Host
       remove-item function:\write-host -ea 0
     }

     function ReplaceWriteHost([string] $Scope)
     {
         Invoke-Expression "function ${scope}:Write-Host { }"
     }

     Cleanup

     # If we are running at the end of a pipeline, need to
     # immediately inject our version into global scope,
     # so that everybody else in the pipeline uses it.
     #
     # This works great, but it is dangerous if we don't
     # clean up properly.
     if($pscmdlet.ParameterSetName -eq 'FromPipeline')
     {
        ReplaceWriteHost -Scope 'global'
     }
   }

   process
   {
      # If a scriptblock was passed to us, then we can declare
      # our version as local scope and let the runtime take it
      # out of scope for us. It is much safer, but it won't
      # work in the pipeline scenario.
      #
      # The scriptblock will inherit our version automatically
      # as it's in a child scope.
      if($pscmdlet.ParameterSetName -eq 'FromScriptBlock')
      {
        . ReplaceWriteHost -Scope 'local'
        & $scriptblock
      }
      else
      {
         # In a pipeline scenario, just pass input along
         $InputObject
      }
   }

   end
   {
      Cleanup
   }
}
$result = .\1.ps1 | Remove-WriteHost

感谢原始功能的“latkin”:)