PowerShell for Windows Admins

Aug 26 2013   1:40PM GMT

String Concatenation revisited

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

There a few ways to concatenate (join together) strings in PowerShell.

The obvious way is to use the concatenation operator +

£> $a = “Hello”
£> $b = “World”
£> $a + ” ” + $b
Hello World

You can use string substitution

£> $a = “Hello”
£> $b = “World”
£> “$a $b”
Hello World

but remember that only works when you are using double quotes. Single quotes give you

£> ‘$a $b’
$a $b

You can also use the format operator –f

£> $a = “Hello”
£> $b = “World”
£> “{0} {1}” -f $a, $b
Hello World

One final method is to put your strings into the elements of an array and use the –join operator

£> $d = @()
£> $d += “Hello”
£> $d += “World”
£> $d
Hello
World
£>
£> $d -join ” ”
Hello World

Which one should you use. Simple, whatever works best to solve your problem.

PowerShell often supplies multiple options to solve a problem. Use whichever you are most comfortable with and is the easiest to use in the context of the problem you are trying to solve.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: