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.ToString() + " - " + $assoc.Name + " - " + $assoc.Owner)
I’d expect this snippet to show:
42 - Slim Shady - Eminem
But instead it shows:
42 + - + Slim Shady + - + Eminem
This makes me think the +
operator isn’t appropriate for concatenating strings and variables.
How should you approach this with PowerShell?
Hey Dharapatel,
To concatenare string in PowerShall you can embed variables directly within double-quoted strings using $().
This allows you to directly insert the value of $assoc.Id, $assoc.Name, and $assoc.Owner into the string without explicitly converting them to strings first.
Write-Host “$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)”
Hope this helped you.
Hello Dipen,
My thoughts here are to concatenate strings in PowerShell you can also use -join operator
The -join operator concatenates an array of strings into a single string, inserting the specified separator (" - " in this case) between each element.
By providing an array containing the values of $assoc.Id, $assoc.Name, and $assoc.Owner, you can concatenate them with the separator.
Write-Host ($assoc.Id, $assoc.Name, $assoc.Owner -join " - ")
Hey Sam,
Can we also use the Format method?
I tried using it below; it worked for me. What are your thoughts on it?
The -f operator is used for string formatting in PowerShell.
You provide a format string (“{0} - {1} - {2}”), where {0}, {1}, and {2} are placeholders for the values to be inserted.
After the format string, you provide the values to insert ($assoc.Id, $assoc.Name, and $assoc.Owner), which will be inserted into the format string in the specified locations.
Write-Host "{0} - {1} - {2}" -f $assoc.Id, $assoc.Name, $assoc.Owner