How to Concatenate Strings and Variables in PowerShell

Microsft PowerShell scripting is little different from the other Programming languages. In most of the programming languages to concatenate a string you will use the operator “+” but in PowerShell, this will not work. So How to Concatenate Strings and Variables in PowerShell.

Let’s take a simple example of Concatenation of String.

If you look at the above example I have a PowerShell object of type employee with Properties ID, FirstName, and LastName. Let’s try to concatenate FirstName and LastName using “+” operator and see what will be the output result.

The “+” operator doesn’t work in the PowerShell for concatenating the Strings and Variables.

In the above example when we tried to concatenate two variables using the + operator it did work and just glued both the strings as HelloWorld. But it doesn’t work in all the case as we see with the objects and properties it just failed.

How to Concatenate Strings and Variables in PowerShell

There are multiple ways to Concatenate Strings in PowerShell. Let’s look at the most efficient  way to perform the PowerShell concatenation.

#1. Expanding Strings

The first approach is very simple and most efficient way to concatenate variables in PowerShell. Use the double quotes instead of the concatenation operator and it works in both the cases. You could easily concatenate anything efficiently.

If you would like to add any characters while appending we could do that easily. Let’s get we need a comma after the first word during concatenation. In order to do that, you just need to add the character after the first variable. Here is the example.,

#2. Substitution or string.Format approach

The expanding strings might be often difficult to read if you have a lengthier code of concatenation. In order to simplify, you can use the string and parameter based approach as shown below.

If you are a c# programmer then you will be very familiar with the above approach. This is similar to string.format approach which we use in C# to concatenate the strings.

You may also like...

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.