Powershell – How to concatenate strings and variables in PowerShell

powershellstring-concatenation

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?

Best Answer

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

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