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?
To concatenate two strings to store in a variable/use in a function, you can use -join.
E.g.
Would assign "John" to $name.
So to output, in one line:
While expression:
will concatenate the strings. You need to put a $ in front of the parenthesis to make it evaluate as a single argument when passed to a powershell command. Example:
As a bonus, if you want it to span multiple lines, then you need to use the ackward backtick syntax at the end of the line (without any spaces or characters to the right of the backtick). Example:
(Actually, I think Powershell is currently implemented a little bit wrong by requires unnecessary back-ticks between parenthesis. If Microsoft would just follow "Python" or "TCL" Parenthesis rules of allowing you to put as many newlines as you want between starting and ending parenthesis then they would solve most of the problems that people don't like about powershell related to line continuation, and concatenation of strings. I've found that you can leave the back-ticks off sometimes on line continuations between parenthesis, but its really flakey and unpredicatable if it will work.. its better to just add the backticks.)
From What To Do / Not to Do in PowerShell: Part 1:
I just want to bring another way to do this using .NET String.Format:
See the Windows PowerShell Language Specification Version 3.0, p34, sub-expressions expansion.
Write-Host can concatenate like this too:
This is the simplest way, IMHO.