Addition in PowerShell

In general, PowerShell is able to detect when a mathematical operation is being performed and convert strings on the fly to permit this:

PS C:\> $x = 10 + “20”
PS C:\> $x
30

However, there are cases where this does not always work as expected:

PS C:\> $x = “1000”
PS C:\> $y = $x + 500
PS C:\> $y
1000500

As you can see, instead of converting the value of $x to an integer and performing the expected addition, it simply treated the entire command as a string concatenation operation. Note, however, that subtraction works just fine:

PS C:\> $z = $x – 500
PS C:\> $z
500

Knowing this, combined with the fact that subtracting the negative of a value is the same as adding the value, we have a workaround:

PS C:\> $y = $x – (-500)
PS C:\> $y
1500

A more straightforward solution, however, is to force PowerShell to treat our variable as an integer:

PS C:\> $y = [int]$x + 500
PS C:\> $y
1500

Leave a Reply