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 + " - " + $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?
Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"
请参阅Windows PowerShell语言规范版本3.0,第34页子表达式扩展。
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).
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
链接地址: http://www.djcxy.com/p/48610.html