I'm trying to figure out what dictates if a value is returned from a PowerShell function or not, and I've run into some oddities. The about_return docs say:
In PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword.
But this seems to glaze over details. If I run this:
function My-Function {
1
[System.Console]::WriteLine("Hello")
$null
$true
$false
0
2
}
Running this returns an array of (along with printing "Hello"):
1
True
False
0
2
Which means that $null isn't auto-returned. Then I tried incrementing since I'm doing using that in a function:
function My-Function {
$n = 1
$n
$n++
($n++)
-join @(1, 2, 3)
(-join @(1, 2, 3))
}
Returns:
1
2
123
123
So, $n and $n++ were returned, but ($n++) wasn't? But then when compared to another operator (-join), it's the same in each case. Why does wrapping parenthesis around $n++ prevent it from being returned, and why don't other operators behave the same? This is even more confusing since the = operator appears to work in the opposite way:
function My-Function {
($n = 1)
$n
$n++
($n++)
}
Returns:
1
1
2
Now wrapping the assignment causes it to be returned, whereas wrapping $n++ causes it to not be returned.
In summary, I'd just like to know a straightforward way of being able to look at a line of code in a function, and determine if it will cause a value to be returned or not.