Monthly Archive

Categories

PowerShell string concatenation

PowerShell string concatenation is performed using the concatenation operator which is +

PS> $a = '1234'
PS> $b = '5678'
PS> $c = $a + $b
PS> $c
12345678

 

When you concatenate 2 strings you’re creating a new string not adding extra characters to the end of the first string.

My preference is to use variable substitution rather than straight concatenation

PS> $d = "$a$b"
PS> $d
12345678

 

If your string has double quote delimiters you can substitute the value of variables as shown. Be careful though because substitution doesn’t work if you use single quotes:

PS> $e = '$a$b'
PS> $e
$a$b

 

One last trick with strings is the ability to use the multiply operator to generate strings

PS> '123' * 5
123123123123123

PS> 1..10 | foreach {'*' * $_}
*
**
***
****
*****
******
*******
********
*********
**********

Comments are closed.