As we know, PowerShell has wacky return semantics.
Function return value in PowerShell shows there are two main ideas to wrap my head around:
- All output is captured, and returned
- The return keyword just indicates a logical exit point
Even things like reserving variables in outer scopes cause output, like [boolean]$isEnabled
. Another good one is $someCollection.Add("toto")
which spits the new collection count. Even Append()
function causes output.
For example :
Function MyFunc {
$res1 = new-object System.Text.StringBuilder
$res1.Append("titi");
$res2 = "toto"
return $res2
}
$s = MyFunc
Write-Host $s
The output is : titi toto
.
The expected output should be toto
.
How to use a powershell function to return the expected value? (at least when viewed from a more traditional programming perspective)