Adding up numbers in PowerShell

2019-05-07 15:54发布

问题:

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:

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


回答2:

$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