Archives

Archives / 2010 / February
  • Powershell output capturing and text wrapping… again…

    A while a go I wrote a post “Powershell output capturing and text wrapping: strange quirks... solved!” on preventing output wrapping in PowerShell when capturing the output. In this article I wrote that I used the following way to capture the output with less probability of wrapping:

    PowerShell -Command  "$host.UI.RawUI.BufferSize = new-object System.Management.Automation.Host.Size(512,50);"c:\temp\testoutputandcapture.ps1" -argument"A value`"" >c:\temp\out.txt 2>&1

    In the above situation I start a PowerShell script, but before doing that I set the buffer size.

    I had some issues with this lately that my values in setting the buffer size where wither to small or too large. The more defensive approach described in the StackOverflow question http://stackoverflow.com/questions/978777/powershell-output-column-width works better for me.

    I use it as follows at the top of my PowerShell script file:

    Prevent text wrapping
    1. set-psdebug -strict -trace 0 #variables must have value before usage
    2. $global:ErrorActionPreference = "Continue" # Stop on errors
    3. $global:VerbosePreference = "Continue" # set to SilentlyContinue to get no verbose output
    4.  
    5. # Reset the $LASTEXITCODE, so we assume no error occurs
    6. $LASTEXITCODE = 0
    7.  
    8. # Update output buffer size to prevent output wrapping
    9. if( $Host -and $Host.UI -and $Host.UI.RawUI ) {
    10. $rawUI = $Host.UI.RawUI
    11. $oldSize = $rawUI.BufferSize
    12. $typeName = $oldSize.GetType( ).FullName
    13. $newSize = New-Object $typeName (512, $oldSize.Height)
    14. $rawUI.BufferSize = $newSize
    15. }