7

I am trying to add up two numbers in PowerShell. I have the input the user gives stored in $Value1 and $Value2. However I can't find any way to actually add these numbers up. I tried using the Measure-Object cmdlet but I can't seem to get it to work.

How does one add up/substract and multiply numbers in Powershell?

1
  • 4
    try get-help about_operators and get-help about_Arithmetic_Operators . Commented Nov 29, 2012 at 16:49

2 Answers 2

13
PS H:\> $value1 = 10
PS H:\> $value2 = 10
PS H:\> $value1 + $value2
20

If your numbers are stored as strings then you'll need to cast them to integers like this:

PS H:\> $value1 = "10"
PS H:\> $value2 = "20"
PS H:\> [int]$value1 + [int]$value2
30
Sign up to request clarification or add additional context in comments.

Comments

4
$val1 = 1
$val2 = 2
$result = $val1 + $val2
$result

If you are getting input from the user, then you would need to explicitly coerce the numbers to be numbers:

[int]$val1 = Read-Host 'Enter value 1'
[int]$val2 = Read-Host 'Enter value 2'
$result = $val1 + $val2
$result

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.