Redirect Write-Host statements to a file

前端 未结 12 1789
鱼传尺愫
鱼传尺愫 2020-11-29 08:39

I have a PowerShell script that I am debugging and would like to redirect all Write-Host statements to a file. Is there an easy way to do that?

12条回答
  •  臣服心动
    2020-11-29 08:49

    I have found the best way to handle this is to have a logging function that will detect if there is a host UI and act accordingly. When the script is executed in interactive mode it will show the details in the host UI, but when it is run via WinRM or in a non-interactive mode it will fall back on the Write-Output so that you can capture it using the > or *> 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"
        }
    }
    

    In cases where you want to capture the full output with the Write-Host coloring, you can use the Get-ConsoleAsHtml.ps1 script to export the host's scrolling buffer to an HTML or RTF file.

提交回复
热议问题