假设我有以下片段:

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


当前回答

$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

其他回答

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

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

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

Output:

Slim Shady, The real slim shady

另一个选项是:

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

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

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

单引号和双引号之间有区别。(我正在使用PowerShell 4)。

你可以这样做(正如本杰明所说):

$name = 'Slim Shady'
Write-Host 'My name is'$name
-> My name is Slim Shady

或者您可以这样做:

$name = 'Slim Shady'
Write-Host "My name is $name"
-> My name is Slim Shady

单引号用于文字,请按如下方式输出字符串。双引号用于需要进行某些预处理时(例如变量、特殊字符等)

So:

$name = "Marshall Bruce Mathers III"
Write-Host "$name"
-> Marshall Bruce Mathers III

鉴于:

$name = "Marshall Bruce Mathers III"
Write-Host '$name'
-> $name

(我发现如何:转义字符、分隔符和引号很适合参考)。

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

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

尝试将要打印的内容包装在括号中:

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

您的代码被解释为传递给Write Host的许多参数。将其包装在括号内将连接值,然后将结果值作为单个参数传递。