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条回答
淡お忘
2楼-- · 2019-01-07 02:24

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"))
查看更多
孤傲高冷的网名
3楼-- · 2019-01-07 02:24

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

查看更多
Deceive 欺骗
4楼-- · 2019-01-07 02:28

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

$id = $assoc.Id
$name = $assoc.Name
$owner = $assoc.owner
"$id - $name - $owner"
查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-07 02:32

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))
查看更多
冷血范
6楼-- · 2019-01-07 02:33
Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"

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

查看更多
唯我独甜
7楼-- · 2019-01-07 02:33

Write-Host can concatenate like this too:

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

This is the simplest way, IMHO.

查看更多
登录 后发表回答