Welcome › Forums › General PowerShell Q&A › Passing an input to a function
- This topic has 1 reply, 2 voices, and was last updated 2 months ago by
Participant.
Viewing 1 reply thread
-
AuthorPosts
-
-
November 20, 2020 at 5:21 am #272899
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?
PowerShell123456789101112function Calc ($a, $b){$res = $a + $breturn $res}$num = Read-Host "Num 1: "$num2 = Read-Host "Num 2: "$res = Calc $num $num2Write-Host $res -
November 20, 2020 at 6:54 am #272926
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:
PowerShell123456789101112function Calc ([int]$a, [int]$b){$res = $a + $breturn $res}$num = Read-Host "Num 1: "$num2 = Read-Host "Num 2: "$res = Calc $num $num2Write-Host $resNote: although I’ve done that in the function defintion, you could also specify the type elsewhere e.g.
PowerShell123456789101112function Calc ($a, $b){$res = $a + $breturn $res}[int]$num = Read-Host "Num 1: "[int]$num2 = Read-Host "Num 2: "$res = Calc $num $num2Write-Host $resor even:
PowerShell123456789101112function Calc ($a, $b){$res = [int]$a + [int]$breturn $res}$num = Read-Host "Num 1: "$num2 = Read-Host "Num 2: "$res = Calc $num $num2Write-Host $res
-
-
AuthorPosts
Viewing 1 reply thread
- You must be logged in to reply to this topic.