【问题标题】:Redirect Write-Host statements to a file将 Write-Host 语句重定向到文件
【发布时间】:2011-04-07 23:10:34
【问题描述】:

我有一个正在调试的 PowerShell 脚本,并且想将所有 Write-Host 语句重定向到一个文件。有没有简单的方法可以做到这一点?

【问题讨论】:

  • 我刚刚发现 Start-Transcript 将所有内容从您的窗口输出到一个文件,但是当我将它添加到 ps1 文件时似乎还没有工作。

标签: powershell


【解决方案1】:

在 PowerShell 4.0 之前,Write-Host 将对象发送到主机。它不返回任何对象。

从 PowerShell 5.0 和更高版本开始,Write-Host 是 Write-Information 的包装器,它允许输出到信息流并使用 6>> file_name 将其重定向。

http://technet.microsoft.com/en-us/library/hh849877.aspx

但是,如果您有很多 Write-Host 语句,请将它们全部替换为 Write-Log,这样您就可以决定是输出到控制台、文件还是事件日志,还是全部三个。

也检查一下:

【讨论】:

  • 我不认为这是一个答案。在 Powershell 3.0 中,如果我尝试 write-host "test" > c:\temp\out.txt 我在文件中什么也得不到。输出写入控制台
  • @ekkis 重定向运算符在应用于没有输出的 cmdlet 时毫无用处,显然
  • 是的,但答案表明,如果我不想替换写主机语句,我应该“尝试附加重定向” - 这是我在答案中尝试的,但失败了跨度>
  • 我明白了,我实际上写了“try”。感谢您的反馈,我希望以更好的指示更正答案。
【解决方案2】:

您可以为Write-Host 创建一个代理函数,它将对象发送到标准输出流,而不仅仅是打印它们。我为此目的编写了以下 cmdlet。它将动态创建一个代理,该代理仅在当前管道的持续时间内持续。

完整的文章在我的博客here 上,但我已经包含了下面的代码。使用-Quiet 开关抑制控制台写入。

用法:

PS> .\SomeScriptWithWriteHost.ps1 | Select-WriteHost | out-file .\data.log  # Pipeline usage
PS> Select-WriteHost { .\SomeScriptWithWriteHost.ps1 } | out-file .\data.log  # Scriptblock usage (safer)

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

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

     [switch] $Quiet
   )

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

     function ReplaceWriteHost([switch] $Quiet, [string] $Scope)
     {
         # Create a proxy for write-host
         $metaData = New-Object System.Management.Automation.CommandMetaData (Get-Command 'Microsoft.PowerShell.Utility\Write-Host')
         $proxy = [System.Management.Automation.ProxyCommand]::create($metaData)

         # Change its behavior
         $content = if($quiet)
                    {
                       # In quiet mode, whack the entire function body,
                       # simply pass input directly to the pipeline
                       $proxy -replace '(?s)\bbegin\b.+', '$Object'
                    }
                    else
                    {
                       # In noisy mode, pass input to the pipeline, but allow
                       # real Write-Host to process as well
                       $proxy -replace '(\$steppablePipeline\.Process)', '$Object; $1'
                    }

         # Load our version into the specified scope
         Invoke-Expression "function ${scope}:Write-Host { $content }"
     }

     Cleanup

     # If we are running at the end of a pipeline, we 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 -Quiet:$quiet -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 -Quiet:$quiet -Scope 'local'
        & $scriptblock
      }
      else
      {
         # In a pipeline scenario, just pass input along
         $InputObject
      }
   }

   end
   {
      Cleanup
   }
}

【讨论】:

    【解决方案3】:

    您可以在辅助 PowerShell shell 中运行脚本并捕获如下输出:

    powershell -File 'Your-Script.ps1' > output.log
    

    这对我有用。

    【讨论】:

    • 效果很好!我发现不需要对代码或代理功能进行任何更改的最佳解决方案。亲吻
    【解决方案4】:

    使用重定向将导致Write-Host 挂起。这是因为 Write-Host 处理特定于当前正在使用的终端的各种格式问题。如果您只想让脚本能够灵活地正常输出(默认为 shell,具有>、2> 等功能),请使用Write-Output。

    否则,如果您真的想捕捉当前终端的特性,Start-Transcript 是一个不错的起点。否则,您将不得不手动测试或编写一些复杂的测试套件。

    【讨论】:

    • 我会提名这个答案为正确答案,因为它基本上表明您不能重定向 write-host,而是建议在其位置使用什么
    • 我认为这应该是公认的答案。我不确定为什么不是? ;)
    【解决方案5】:

    这适用于我几天前编写的第一个 PowerShell 脚本:

    function logMsg($msg)
    {
        Write-Output $msg
        Write-Host   $msg
    }
    

    在脚本中的使用:

    logMsg("My error message")
    logMsg("My info message")
    

    PowerShell 脚本执行调用:

    ps> .\myFirstScript.ps1 >> testOutputFile.txt
    

    这并不完全是对这个问题的回答,但它可能会帮助那些试图同时实现登录到控制台和输出到某个日志文件的人,做我在这里达到的 :)

    【讨论】:

    • 谨慎使用这种方法。您使用 write-output 编写的任何内容都会成为函数返回值的一部分,这可能会令人惊讶,尤其是如果函数后面有明确的 return 语句。
    【解决方案6】:

    尝试在尖括号> 前添加星号* 以重定向所有流:

    powershell -File Your-Script.ps1 *> output.log

    当请求流重定向时,如果没有指定特定流,则默认情况下仅重定向 Success Stream(1>)。 Write-Host 是Write-Information 的别名,它写入Information Stream (6>)。要重定向所有流,请使用*>。

    Powershell-7.1支持多个输出流的重定向:

    • 成功流 (#1):PowerShell 2.0 Write-Output
    • 错误流 (#2):PowerShell 2.0 Write-Error
    • 警告流 (#3):PowerShell 3.0 Write-Warning
    • 详细流 (#4):PowerShell 3.0 Write-Verbose
    • 调试流 (#5):PowerShell 3.0 Write-Debug
    • 信息流 (#6):PowerShell 5.0 Write-Information
    • 所有流 (*):PowerShell 3.0

    【讨论】:

      【解决方案7】:

      定义一个名为 Write-Host 的函数。让它写入文件。如果某些调用使用一组奇怪的参数,您可能会遇到一些麻烦。此外,这仅适用于非 Snapin 限定的调用。

      【讨论】:

        【解决方案8】:

        如果您只有几个 Write-Host 语句,您可以使用 "6>>" 重定向器操作符到一个文件:

        Write-Host "Your message." 6>> file_path_or_file_name

        这是微软提供的"Example 5: Suppress output from Write-Host",相应修改为about_Operators。

        【讨论】:

        • “6”表示:“信息流。在 PowerShell 5.0 中引入。”
        【解决方案9】:

        我刚刚在脚本顶部添加了Start-Transcript,在底部添加了Stop-Transcript。

        输出文件原本打算命名为<folder where script resides>-<datestamp>.rtf,但由于某种原因,跟踪文件被放到了我没想到的地方——桌面!

        【讨论】:

          【解决方案10】:

          如果您希望将消息保存在文件中,则不应使用 Write-Host。它仅用于写入主机。

          相反,您应该使用日志记录模块,或 Set/Add-Content。

          【讨论】:

            【解决方案11】:

            我发现处理此问题的最佳方法是拥有一个日志功能,该功能将检测是否存在主机 UI 并采取相应措施。当脚本在交互模式下执行时,它将在主机 UI 中显示详细信息,但当它通过 WinRM 或在非交互模式下运行时,它将退回到Write-Output,以便您可以使用 @ 捕获它987654326@或*>redirection operators

            function Log-Info ($msg, $color = "Blue") {
                if($host.UI.RawUI.ForegroundColor -ne $null) {
                    Write-Host "`n[$([datetime]::Now.ToLongTimeString())] $msg" -ForegroundColor $color -BackgroundColor "Gray"
                } else {
                    Write-Output "`r`n[$([datetime]::Now.ToLongTimeString())] $msg"
                }
            }
            

            如果您想使用Write-Host 着色捕获完整输出,可以使用Get-ConsoleAsHtml.ps1 脚本将主机的滚动缓冲区导出到HTML 或RTF 文件。

            【讨论】:

            • 如果有人在管道或函数中使用 Log-Info 函数,写入输出可能会很危险。然后,您将突然在管道中获得控制台输出或作为函数返回值。
            【解决方案12】:

            使用Write-Output 而不是Write-Host,并将其重定向到这样的文件:

            Deploy.ps1 > mylog.log or Write-Output "Hello World!" > mylog.log
            

            【讨论】:

              【解决方案13】:

              尝试使用Write-Output 而不是Write-Host。

              输出沿着管道传输,但如果这是管道的末端,它会进入控制台。

              > Write-Output "test"
              test
              > Write-Output "test" > foo.txt
              > Get-Content foo.txt
              test
              

              【讨论】:

                猜你喜欢
                • 2021-06-03
                • 2012-03-06
                • 2018-07-03
                • 2015-05-19
                • 1970-01-01
                • 2020-02-03
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多