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?
(Current PS version 5.1.17134.407)
It's all said and done by now I guess but this also works as of now:
Another option is:
The "best" method is probably the one C.B. suggested:
Concatenate strings just like in the DOS days. This is a big deal for logging so here you go:
I seem to struggle with this (and many other unintuitive things) every time I use PowerShell after time away from it, so I now opt for:
These answers all seem very complicated. If you are using this in a PowerShell script you can simply do this:
It will output
Note how a space is put between the words for you
You need to place the expression in parentheses to stop them being treated as different parameters to the cmdlet: