假设我有以下片段:

$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中的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的许多参数。将其包装在括号内将连接值,然后将结果值作为单个参数传递。

每次我在离开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"

您还可以访问C#/.NET方法,以下方法也适用:

$string1 = "Slim Shady, "
$string2 = "The real slim shady"

$concatString = [System.String]::Concat($string1, $string2)

Output:

Slim Shady, The real slim shady