PowerShell function to find the square of a number:
In addition to the Alistair's answer about converting, the string
returned by Read-Host
to int
, you might want to use the Math library to square the value.
Sample Code
function Get-Square([int] $value){ $result = [Math]::Pow($value,2) return $result}$value = Read-Host 'Enter a value'$result = Get-Square $valueWrite-Output "$value * $value = $result"
Results
Enter a value: 4
4 * 4 = 16
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:
function Get-Square([int]$value){ $result = $value * $value return $result}$value = Read-Host 'Enter a value'$result = Get-Square $valueWrite-Output "$value * $value = $result"
It is like "4" * "4", and PowerShell converts the second "4" to int, so it returns "4444".
4 * 4 = 16"4" * "4" = "4444""4" * 4 = "4444"4 * "4" = 16