假设我有以下片段:

$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版本5.1.17134.407)

截至目前,这也有效:

$myVar = "Hello"

echo "${myVar} World"

注意:这只适用于双引号

其他回答

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

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

另一个选项是:

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

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

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

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

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

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

只是为了好玩。您还可以直接访问PSObject的值,如下所示:

$assoc.psobject.Properties.value -join " - "

但如果未指定对象的顺序,PowerShell将以随机顺序显示值。因此,您应该添加标记[ordered]:

$assoc = [pscustomobject] [ordered] @{
    Id = 42
    Name = "Slim Shady"
    Owner = "Eminem"
}
$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