How do I concatenate strings and variables in Powe

2019-01-07 01:41发布

问题:

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?

回答1:

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

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



回答2:

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):

$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

(http://ss64.com/ps/syntax-esc.html I find good for reference).



回答3:

One way is:

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

Another one is:

Write-host  ("{0}  -  {1}  -  {2}" -f $assoc.Id,$assoc.Name,$assoc.Owner )

Or just (but I don't like it ;) ):

Write-host $assoc.Id  "  -  "   $assoc.Name  "  -  "  $assoc.Owner


回答4:

To concatenate two strings to store in a variable/use in a function, you can use -join.

E.g.

$name = -join("Jo", "h", "n");

Would assign "John" to $name.

So to output, in one line:

Write-Host (-join("Jo", "h", "n"))


回答5:

Try wrapping whatever you want to print out in parenthesis:

Write-host ($assoc.Id + "  -  "  + $assoc.Name + "  -  " + $assoc.Owner)

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.



回答6:

Another option is:

$string = $assoc.ID
$string += " - "
$string += $assoc.Name
$string += " - "
$string += $assoc.Owner
Write-Host $string

The "best" method is probably the one C.B. suggested:

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


回答7:

You need to place the expression in parentheses to stop them being treated as different parameters to the cmdlet:

Write-host ($assoc.Id + "  -  "  + $assoc.Name + "  -  " + $assoc.Owner)


回答8:

While expression:

"string1" + "string2" + "string3"

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:

Write-Host $( "string1" + "string2" + "string3" ) 

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:

Write-Host $(`
    "The rain in "        +`
    "Spain falls mainly " +`
    "in the plains"       )`
    -ForegroundColor Yellow

(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.)



回答9:

Here is another way as an alternative:

Write-host (" {0}  -  {1}  -  {2}" -f $assoc.Id, $assoc.Name, $assoc.Owner)


回答10:

I just want to bring another way to do this using .NET String.Format:

$name = "Slim Shady"
Write-Host ([string]::Format("My name is {0}", $name))


回答11:

From What To Do / Not to Do in PowerShell: Part 1:

$id = $assoc.Id
$name = $assoc.Name
$owner = $assoc.owner
"$id - $name - $owner"


回答12:

These answers all seem very complicated. If you are using this in a PowerShell script you can simply do this:

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

It will output

My name is Slim Shady

Note how a space is put between the words for you



回答13:

Concatenate strings just like in the DOS days. This is a big deal for logging so here you go:

$strDate = Get-Date
$strday = "$($strDate.Year)$($strDate.Month)$($strDate.Day)"

Write-Output "$($strDate.Year)$($strDate.Month)$($strDate.Day)"
Write-Output $strday


回答14:

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:

[string]::Concat("There are ", $count, " items in the list")


回答15:

Write-Host can concatenate like this too:

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

This is the simplest way, IMHO.



回答16:

(Current PS version 5.1.17134.407)

It's all said and done by now I guess but this also works as of now:

$myVar = "Hello"

echo "${myVar} World"


回答17:

Try this:

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