Passing an input to a function

Hello, I’m just getting used to Powershell. When I execute the script and enter the numbers 4 and 5 in the 2 queries I expect to get 9 at the end of the script but I only get 45. If I pass these numbers directly hard-coded to the function then there are no problems. Does anyone have an idea what I am doing wrong?

function Calc ($a, $b)
{
$res = $a + $b
return $res
}

$num = Read-Host "Num 1: "
$num2 = Read-Host "Num 2: "

$res = Calc $num $num2

Write-Host $res

 

What’s happening here is that $a and $b are actually String objects. So the + operator is joining the string ‘5’ to the string ‘4’ and giving you ‘45’. You need to specify that the inputs are integers:

function Calc ([int]$a, [int]$b)
{
$res = $a + $b
return $res
}
 
$num = Read-Host "Num 1: "
$num2 = Read-Host "Num 2: "
 
$res = Calc $num $num2
 
Write-Host $res

Note: although I’ve done that in the function defintion, you could also specify the type elsewhere e.g.

function Calc ($a, $b)
{
$res = $a + $b
return $res
}
 
[int]$num = Read-Host "Num 1: "
[int]$num2 = Read-Host "Num 2: "
 
$res = Calc $num $num2
 
Write-Host $res

or even:

function Calc ($a, $b)
{
$res = [int]$a + [int]$b
return $res
}
 
$num = Read-Host "Num 1: "
$num2 = Read-Host "Num 2: "
 
$res = Calc $num $num2
 
Write-Host $res