假设我有以下片段:

$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实现这一点?


当前回答

以下是另一种替代方法:

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

其他回答

我只想用另一种方式使用.NET字符串来实现这一点。格式:

$name = "Slim Shady"
Write-Host ([string]::Format("My name is {0}", $name))
$assoc = @{
    Id = 34
    FirstName = "John"
    LastName = "Doe"
    Owner = "Wife"
}

$assocId = $assoc.Id
$assocFN = $assoc.FirstName
$assocLN = $assoc.LastName
$assocName = $assocFN, $assocLN -Join " "
$assocOwner = $assoc.Owner

$assocJoin = $assocId, $assocName, $assocOwner -join " - "
$assocJoin
#Output = 34 - John Doe - Wife

一种方法是:

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
Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"

请参阅Windows PowerShell语言规范3.0版p34子表达式扩展。

(当前PowerShell版本5.1.17134.407)

截至目前,这也有效:

$myVar = "Hello"

echo "${myVar} World"

注意:这只适用于双引号