How do I concatenate strings and variables in PowerShell?

Suppose I have the following snippet:

$assoc = New-Object PSObject -Property @{
    Id = 42
    Name = "Slim Shady"
    Owner = "Eminem"
}

Write-Host $assoc.Id + "  -  "  + $assoc.Name + "  -  " + $assoc.Owner

I'd expect this snippet to show:

42 - Slim Shady - Eminem

But instead it shows:

42 + - + Slim Shady + - + Eminem

Which makes me think the + operator isn't appropriate for concatenating strings and variables.

How should you approach this with PowerShell?


Solution 1:

Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"

See the Windows PowerShell Language Specification Version 3.0, p34, sub-expressions expansion.

Solution 2:

There is a difference between single and double quotes. (I am using PowerShell 4).

You can do this (as Benjamin said):

$name = 'Slim Shady'
Write-Host 'My name is'$name
-> My name is Slim Shady

Or you can do this:

$name = 'Slim Shady'
Write-Host "My name is $name"
-> My name is Slim Shady

The single quotes are for literal, output the string exactly like this, please. The double quotes are for when you want some pre-processing done (such as variables, special characters, etc.)

So:

$name = "Marshall Bruce Mathers III"
Write-Host "$name"
-> Marshall Bruce Mathers III

Whereas:

$name = "Marshall Bruce Mathers III"
Write-Host '$name'
-> $name

(I find How-to: Escape characters, Delimiters and Quotes good for reference).

Solution 3:

You can also use -join

E.g.

$var = -join("Hello", " ", "world");

Would assign "Hello world" to $var.

So to output, in one line:

Write-Host (-join("Hello", " ", "world"))

Solution 4:

One way is:

Write-Host "$($assoc.Id)  -  $($assoc.Name)  -  $($assoc.Owner)"

Another one is:

Write-Host  ("{0}  -  {1}  -  {2}" -f $assoc.Id,$assoc.Name,$assoc.Owner )

Or just (but I don't like it ;) ):

Write-Host $assoc.Id  "  -  "   $assoc.Name  "  -  "  $assoc.Owner

Solution 5:

Try wrapping whatever you want to print out in parentheses:

Write-Host ($assoc.Id + "  -  "  + $assoc.Name + "  -  " + $assoc.Owner)

Your code is being interpreted as many parameters being passed to Write-Host. Wrapping it up inside parentheses will concatenate the values and then pass the resulting value as a single parameter.