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?
Try this:
No one seems to have mentioned the difference between single and double quotes. (I am using PowerShell 4).
You can do this (as @Ben said):
Or you can do this:
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:
Whereas:
(http://ss64.com/ps/syntax-esc.html I find good for reference).
One way is:
Another one is:
Or just (but I don't like it ;) ):
Here is another way as an alternative:
Try wrapping whatever you want to print out in parenthesis:
Your code is being interpreted as many parameters being passed to
Write-Host
. Wrapping it up inside parenthesis will concatenate the values and then pass the resulting value as a single parameter.