Finding Unwanted Output

by Oct 1, 2009

PowerShell has an extremely flexible way of submitting return values. Instead of explicitly setting the return value of a function, PowerShell simply returns anything outputted and left behind. If there is more than one result, it is wrapped as an array. While this is great, sometimes methods return information that isn't supposed to be output. Functions will return more information than you planned if you forget to clean this up by sending it to Out-Null or casting the return value to [void]. Here is an example:

function test {
[System.Reflection.Assembly]::LoadWithPartialName(
'Microsoft.VisualBasic')
"This is my return value"
}

You will not only get the return value you expected when you call "test," but also the result returned by LoadWithPartialName(). Now, to eliminate the problem, you could vaporize the unwanted result like this:

function test {
[System.Reflection.Assembly]::LoadWithPartialName(
'Microsoft.VisualBasic') | Out-Null
"This is my return value"
}

But how do you find all the spots that return data so you can check who is responsible for unwanted output? You can automatically set breakpoints on commands in PowerShell v.2. This is what to look for since all output is delivered by Out-Default:

$null = Set-PSBreakPoint -Command Out-Default

When you call your function again, the debugger will stop at each instance that returns data.

Twitter This Tip! ReTweet this Tip!