1

I have two functions:

Function1
{
    Function2
    return 1
}

Function2
{
    return 0
}

After executing Function1 it should return 1, but it returns 0. Why is that?

3
  • I really don't understand what you're asking. What are you expecting Function1 to return and what is it returning? Commented Apr 11, 2013 at 18:11
  • after executing Function1 it shoulf return value 1 but it returns value 0. Commented Apr 11, 2013 at 18:18
  • How are you calling Function1 and how are you detecting its return value? Commented Apr 11, 2013 at 18:55

2 Answers 2

11

PowerShell "return values" don't really work the way you'd be used to from other languages. The important thing to remember is that all output is captured and returned. The return statement is basically just a logical exit point.

For example:

Function Return-Zero {
    return 0
}

Function Return-One {
    Return-Zero
    return 1
}

Return-One

Since the return value of Return-Zero was not stored in a variable, it is part of the output. Running the above will have the output:

0
1

...which is probably what you're getting. If you store the return of Return-Zero in a variable, it is not part of the output.

Function Return-Zero {
    return 0
}

Function Return-One {
    $var = Return-Zero
    return $var
}

Return-One

Output of the above is 0.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I was having the same problem. So do you know of any way to actually return the thing that you want, discarding other outputs. Outputs are hard to capture in your way because you dont know if a statement will return any value or not.
The actual code would dictate the best way to go about it. If you have an example to post, that would be helpful.
0

Are you sure it continues to run, and that it only returns 0? It should return 0 (the return from function 2), then return 1, and exit.

1 Comment

no it returns 0 and continues to run..if m not wrong sine the Funtion1 has got return 0 from Function2 call it ignores the return 1...is that possible...have i missed something...but when i assign the Function2 cqll in Funtion1 to a variable the funtion1 exits properly...y this strange behaviour...is there a precedence of return value or something...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.