PSMonday #4: Monday, May 23, 2016

Topic: Add and Concatenate Numbers and Strings

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

In last week’s PSMonday we determined that numbers can be strings, but that when they are, they lose their numeric properties. As strings, they don’t and won’t act like numbers anymore. For instance, if you “add” the string ‘5’ plus the string ‘5’ you’re not going to get 10. As the plus sign is also a concatenation operator, you end up with the string value of ’55’.

'5' + '5'

55

If you were working with numeric values, such as 5 + 5 — notice there’s no quotes around those digits — then you would get the numeric result of 10.

5 + 5

10

Now that we know what happens when we concatenate two strings and add two numbers, you might wonder what happens when we do this with a string, and a number.

Here’s the key: The object on the left decides what happens. In the first below example, the numeric value on the left coerces the string value on the right into becoming a number, and then the numbers are added. In the second example, we see the opposite. The string value on the left coerces the number on the right into being a string, and then the strings are concatenated.

5 + '5'

10

'5' + 5

55

Expect this to fail at times. In the next example, the number on the left cannot coerce the string value “string” into becoming a numeric value — it’s not possible — and therefore it fails.

5 + 'string'

Cannot convert value "string" to type "System.Int32". Error: "Input string was not in a correct format."

Had this been written in reverse, as it is below, it would work and the result would be ‘string5’. This is because the numeric value 5 can become the string value ‘5’, as we saw earlier.

'string' + 5

string5

Short and sweet today; thanks for reading this PSMonday.

Leave a Reply

Your email address will not be published. Required fields are marked *