How do I concatenate strings and variables in PowerShell? How do I concatenate strings and variables in PowerShell? powershell powershell

How do I concatenate strings and variables in PowerShell?


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

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


There is a difference between single and double quotes. (I am using PowerShell 4).

You can do this (as Benjamin said):

$name = 'Slim Shady'Write-Host 'My name is'$name-> My name is Slim Shady

Or you can do this:

$name = 'Slim Shady'Write-Host "My name is $name"-> My name is Slim Shady

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:

$name = "Marshall Bruce Mathers III"Write-Host "$name"-> Marshall Bruce Mathers III

Whereas:

$name = "Marshall Bruce Mathers III"Write-Host '$name'-> $name

(I find How-to: Escape characters, Delimiters and Quotes good for reference).


You can also use -join

E.g.

$var = -join("Hello", " ", "world");

Would assign "Hello world" to $var.

So to output, in one line:

Write-Host (-join("Hello", " ", "world"))