odd interaction between function and return

Topics: Developer Forum
Nov 20, 2007 at 4:03 PM
Maybe this is a newbie question...
I am trying to understand the how the return values for functions in Powershell are supposed to work.

I defined a simple function in a script file.

function foo( string $ss ) {
$sb = new "System.Text.StringBuilder"
$sb.Append( $ss )
return $sb
}


I dot sourced it and then
> . .\test.ps1
>$x = foo "abc"
>$x


Capacity MaxCapacity Length
-------- ----------- ------
16 2147483647 1
16 2147483647 1

$x is an array of objects with TWO elements.
First in the function I returned the string builder, not an array....
Second the string builder is in the array twice.
Huh?
Nov 21, 2007 at 5:25 AM
Welcome to the fold.

It's a common mistake. What you need to know is that a function returns ALL uncaptured output. The string Append() method returns a StringBuilder object (actually, the same Stringbuilder object). This is a convenience so that you can do things like

$sb.Append("this").Append("is").Append("cool")

So your statement

$sb.Append($ss)

returned a stringbuilder object. Since it wasn't captured, out it goes with the rest of the function result.

When you want to discard a result, cast it to void. So a rewrite would be:

function foo( string $ss ) {
$sb = new "System.Text.StringBuilder"
void $sb.Append( $ss )
return $sb
}

In fact, the "return" statement is not necessary either, so here's another re-write:

function foo( string $ss ) {
$sb = new "System.Text.StringBuilder"
void $sb.Append( $ss )
$sb
}


But on reflection, I see that that's silly, it should just be:

function foo( string $ss ) {
$sb = new "System.Text.StringBuilder"
$sb.Append( $ss )
}

BTW, a more appropriate forum for your PS questions would be microsoft.public.windows.powershell. here's the ugly URL I snipped for it:

http://www.microsoft.com/communities/newsgroups/list/en-us/default.aspx?dg=microsoft.public.windows.powershell&cat=enus4200CF39-8075-8AEF-F08A-B4D1E076AE83&lang=en&cr=us
Nov 21, 2007 at 1:54 PM
Thanks Leo!
I also found this really good blog entry
"Function Output Consists of Everything That Isn't Captured"
http://keithhill.spaces.live.com/blog/cns!5A8D2641E0963A97!811.entry

Karl