How do I concatenate strings and variables in Powe

2019-01-07 01:56发布

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?

17条回答
forever°为你锁心
2楼-- · 2019-01-07 02:33

Try this:

$name = "Slim Shady"
Write-Host "My name is " $name
查看更多
贪生不怕死
3楼-- · 2019-01-07 02:35

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

查看更多
看我几分像从前
4楼-- · 2019-01-07 02:36

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
查看更多
家丑人穷心不美
5楼-- · 2019-01-07 02:38

Here is another way as an alternative:

Write-host (" {0}  -  {1}  -  {2}" -f $assoc.Id, $assoc.Name, $assoc.Owner)
查看更多
Summer. ? 凉城
6楼-- · 2019-01-07 02:39

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.

查看更多
登录 后发表回答