假设我有以下片段:

$assoc = New-Object PSObject -Property @{
    Id = 42
    Name = "Slim Shady"
    Owner = "Eminem"
}

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

我希望这段代码显示:

42-Slim Shady-阿姆

但相反,它显示:

42+-+斯利姆·沙迪+-+埃米纳姆

这让我觉得+运算符不适合连接字符串和变量。

您应该如何使用PowerShell实现这一点?


当前回答

每次我在离开PowerShell之后使用PowerShell时,我似乎都会纠结于这个问题(以及其他许多不直观的事情),所以我现在选择:

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

其他回答

从PowerShell中的What To Do/Not To Do:第1部分:

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

如其他地方所述,可以使用join。

如果您使用命令作为输入(就像我一样),请使用以下语法:

-join($(Command1), "," , $(Command2))

这将导致两个输出用逗号分隔。

看见https://stackoverflow.com/a/34720515/11012871相关评论

一种方法是:

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

另一个是:

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

或者只是(但我不喜欢;):

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

您需要将表达式放在括号中,以防止它们被视为cmdlet的不同参数:

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

写主机也可以这样连接:

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

这是最简单的方法,IMHO。