PowerShell string concatenation

Strings –  a list of characters such as ‘abcd’ – are a common feature of programming or scripting. Sometimes you need to join – concatenate – two or more strings together. This is how PowerShell string concatenation works.

First you need to know that strings can be defined with single quotes or double quotes:

PS> $sq = ‘A single quoted string’
PS> $sq
A single quoted string

PS> $dq = “A double quoted string”
PS> $dq
A double quoted string

The difference is that you can substitute into a double quoted string. Best practice is to use single quotes UNLESS you intend to substitute into the string

PS> ‘I am $sq’
I am $sq
PS> “I am $sq”
I am A single quoted string

String concatenation can be performed using the concatenation operator – a plus sign or through string substitution

PS> $s1 = ‘abcd’ + ‘defg’
PS> $s1
abcddefg

You can use variables

PS> $s1 = ‘abcd’
PS> $s2 = ‘defg’
PS> $s3 =  $s1 + $s2
PS> $s3
abcddefg

When you concatenate strings like this you’re actually creating a new string not extending an existing one.

Alternatively, use string substitution

PS> $s4 = “$s1$s2”
PS> $s4
abcddefg

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

One Response to PowerShell string concatenation

  1. skolvikings says:

    One thing I’ve frequently run into when substituting into a double-quoted string is that some special characters immediately adjacent to the variable can cause issues. Also if you’re inserting a property of an object “e.g. $a.name” into the string, that can also cause issues if it’s adjacent to other characters. I get around those issues by using $($a.name) or $($a), etc.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s