Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell returns wrong result

I came across this weird issue in Powershell (not in other languages). Could anyone please explain to me why this happened?

I tried to return a specified number (number 8), but the function keeps throwing everything at me. Is that a bug or by design?

Function GetNum() {
   Return 10
}

Function Main() {

    $Number10 = GetNum
    $number10 #1 WHY NO OUTPUT HERE ??????? I don't want to use write host
    $result = 8  # I WANT THIS NUMBER ONLY
    PAUSE
    return $result
}

do {    
    $again = Main
    Write-Host "RESULT IS "$again # Weird Result, I only want Number 8
} While ($again -eq 10) # As the result is wrong, it loops forever
like image 388
romeo.Do Avatar asked Feb 28 '26 23:02

romeo.Do


1 Answers

Is that a bug or by design?

By design. In PowerShell, cmdlets can return a stream of objects, much like using yield return in C# to return an IEnumerable collection.

The return keyword is not required for output values to be returned, it simply exits (or returns from) the current scope.

From Get-Help about_Return (emphasis added):

    The Return keyword exits a function, script, or script block. It can be
    used to exit a scope at a specific point, to return a value, or to indicate
    that the end of the scope has been reached.


    Users who are familiar with languages like C or C# might want to use the
    Return keyword to make the logic of leaving a scope explicit.


    In Windows PowerShell, the results of each statement are returned as
    output, even without a statement that contains the Return keyword.
    Languages like C or C# return only the value or values that are specified
    by the Return keyword.
like image 101
Mathias R. Jessen Avatar answered Mar 04 '26 09:03

Mathias R. Jessen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!