How to redirect Powershell output from a script ru

2020-07-06 06:47发布

问题:

I have a powershell script which is invoked by the task scheduler. The task's definition also redirects the output using >> to a log file. The PowerShell script invokes a C# console program which generates output which is longer than 80 characters in width. However, the resultant output in the log file is wrapping all the output from the C# program to 80- characters. Note that only the output from the C# program is wrapped. All other output from the script (generated by Write-Host) is not wrapped. Also note that this wrapping only occurs when the script is run by the task scheduler.

Here is the script calling chain:

  • The task definition invokes a .cmd script (RunWidthTest.cmd)

  • RunWidthTest.cmd: powershell -File .\RunReports.ps1 >> C:\Log\output.log

  • RunReports.ps1 (snippet):

    Write-Host "======================================================== Running reports for date file for $valueDate"

    .\ReportRunner.exe --ValueDate $valueDate | Out-Default

Note that piping the outout to Out-Default is required to avoid another powershell error that occurs due to the fact that an executable's output is attempting to write to the same stream as the powershell script without powershell being aware of it (Write-Host : The OS handle's position is not what FileStream expected. Do not use a handle simultaneously in one FileStream and in Win32 code or another FileStream. This may cause data loss.)

So in this case here, the string output by the Write-Host line is not wrapped, however, any output generated by ReportRunner.exe is wrapped to 80 characters and it only occurs when run with the task scheduler! The same behaviour occurs if you change the point at which the redirection occurs, ie if you redirect in the definition the task (the task's command line instead of inside the script)

Any clues as to why this would occur and how to override this width restriction.

Thanks.

回答1:

Did you try

| Out-File C:\Log\output.log -width 120 # or whatever size  you need


回答2:

Scripting Guy to the rescue!

Link: How can I expand the width of the Windows PowerShell Console

This worked for me:

# Change the PS host parameters, so that log file width is wider than 80 characters
$PSHost  = Get-Host
$PSWindow = $PSHost.UI.RawUI
$PSBuffer = $PSWindow.BufferSize
$PSBuffer.Height = 3000
$PSBuffer.Width = 150
$PSWindow.BufferSize = $PSBuffer
$PSBuffer = $PSWindow.WindowSize
$PSBuffer.Height = 50
$PSBuffer.Width = 150
$PSWindow.WindowSize = $PSBuffer


回答3:

I had a very similar situation, and neither of the other answers worked for me. The only way I was able to get it to work was to use the mode command:

mode con cols=120

& C:\path\to\app.exe parameter1 parameter2 | Out-File 'C:\path\to\file.txt' -Encoding Utf8