Question:
This is my function for finding the square of a value:
1 2 3 4 5 6 7 8 9 10 |
function Get-Square($value) { $result = $value * $value return $result } $value = Read-Host 'Enter a value' $result = Get-Square $value Write-Output "$value * $value = $result" |
1234 PS C:\Users> .\Get-Time.ps1Enter a value: 44 * 4 = 4444
Why is the result 4444 and not 16? Thank you.
Answer:
It seems that Read-Host
is returning a string, and a string times any value in powershell, results in string repeated value times. You need to make powershell treat $value
as an integer. Try this:
1 2 3 4 5 6 7 8 9 10 |
function Get-Square([int]$value) { $result = $value * $value return $result } $value = Read-Host 'Enter a value' $result = Get-Square $value Write-Output "$value * $value = $result" |