PowerShell: Write-Verbose and Write-Debug without annoying word wrap

Recently I ran into an issue with the PowerShell runner in TeamCity. I wanted to use the Write-Verbose and Write-Debug cmdlets to conditionally output some messages. However I discovered that the output in the build log was anything but what I originally had planned. The messages where “cut off” or word-wrapped so to say in various places. Here’s a look at the problem and how I’ve solved it.

Problem

To put this to the test here’s what I’ll do:

I’ll fire up a PowerShell runner and output the exact same message (a long one) using Write-Host, Write-Debug, and finally Write-Verbose.

image

And here’s the result:

image

Write-Host: outputs the whole message, perfect!
Write-Debug and Write-Verbose: word wraps the message at various random parts. deleting file | [C:TeamCity….etc.] | Flow\TestResults.txt

Solution

There are numerous of explanations and examples of handling situations that resemble this one online. I’m just simply going to show you how I’ve solved it.
Put this before you code that’s going to write the output:

$max = $host.UI.RawUI.MaxPhysicalWindowSize
$host.UI.RawUI.BufferSize = New-Object System.Management.Automation.Host.Size(9999,9999)
$host.UI.RawUI.WindowSize = New-Object System.Management.Automation.Host.Size($max.Width,$max.Height)

Line 1 figures out the maximum size, which can differ from your environment to TeamCity. I think TeamCity has max width of 128 but who cares.
Next, set the buffer (important to be first) and then the new window size.

Here’s a more “advanced version” that doesn’t fire if you’re not in TeamCity land:

function Set-PSConsole {
  try {
		$max = $host.UI.RawUI.MaxPhysicalWindowSize
		if($max) {
		$host.UI.RawUI.BufferSize = New-Object System.Management.Automation.Host.Size(9999,9999)
		$host.UI.RawUI.WindowSize = New-Object System.Management.Automation.Host.Size($max.Width,$max.Height)
	}
	} catch {}
}
if ($env:TEAMCITY_VERSION) {
	Set-PSConsole
}

Oh yeah…here’s the new and improved result:

image

Ah, that feels better…!

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: