Quantcast
Channel: Active questions tagged return-value - Stack Overflow
Viewing all articles
Browse latest Browse all 230

What decides if a value is returned from a PowerShell function?

$
0
0

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"):

1TrueFalse02

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:

12123123

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:

112

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.


Viewing all articles
Browse latest Browse all 230

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>