PowerShell Math Problem?

function other3($x, $y)
{
    $tmp = $x + $y
    return $tmp
}

$x = 5
$y = 10

$a = other3($x, $y)
Write-Host $a

5 10 keeps returning, when he should return 15, what is the deal?

+3
source share
2 answers

To call other3 with two parameters, drop the brace "()", for example.

$a = other3 $x  $y

The way you are currently calling it actually passes one parameter, an array with two elements, i.e. 5 and 10. The second parameter is empty (probably defaults to null), which means that adding does nothing, and you simply return the $ x Parameter.

+10
source

You pass the list (5,10) to the parameter $ x and $ null in $ y.

When the function adds $ null to the list, you just get the list back.

Adding some write-write statements to a function should make this clear:

function other3($x, $y)
{
    $tmp = $x + $y
    write-host "`x=($x)"
    write-host "`y=($y)"
    return $tmp
}

$x = 5
$y = 10

$a = other3($x, $y)
Write-Host $a
+2
source

All Articles