假设我有以下片段:

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

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

其他回答

您也可以使用-join

E.g.

$var = -join("Hello", " ", "world");

将为$var分配“Hello world”。

因此,在一行中输出:

Write-Host (-join("Hello", " ", "world"))

连接字符串就像在DOS时代一样。这对日志记录来说是一件大事,因此您可以:

$strDate = Get-Date
$strday = "$($strDate.Year)$($strDate.Month)$($strDate.Day)"

Write-Output "$($strDate.Year)$($strDate.Month)$($strDate.Day)"
Write-Output $strday

另一个选项是:

$string = $assoc.ID
$string += " - "
$string += $assoc.Name
$string += " - "
$string += $assoc.Owner
Write-Host $string

“最佳”方法可能是C.B.建议的方法:

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

以下是另一种替代方法:

Write-Host (" {0}  -  {1}  -  {2}" -f $assoc.Id, $assoc.Name, $assoc.Owner)
$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