如何在PowerShell中连接字符串和变量?
本文翻译自:How do I concatenate strings and variables in PowerShell?
Suppose I have the following snippet: 假设我有以下代码段:
$assoc = New-Object psobject -Property @{
Id = 42
Name = "Slim Shady"
Owner = "Eminem"
}
Write-host $assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner
I'd expect this snippet to show: 我希望这个代码片段显示出来:
42 - Slim Shady - Eminem
But instead it shows: 但是它显示:
42 + - + Slim Shady + - + Eminem
Which makes me think the +
operator isn't appropriate for concatenating strings and variables. 这使我认为+
运算符不适用于连接字符串和变量。
How should you approach this with PowerShell? 如何使用PowerShell处理此问题?
#1楼
参考:https://stackoom.com/question/11Pgj/如何在PowerShell中连接字符串和变量
#2楼
您需要将表达式放在括号中,以防止将它们视为与cmdlet不同的参数:
Write-host ($assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner)
#3楼
Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"
请参阅Windows PowerShell语言规范版本3.0 ,p34,子表达式扩展。
#4楼
One way is: 一种方法是:
Write-host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"
Another one is: 另一个是:
Write-host ("{0} - {1} - {2}" -f $assoc.Id,$assoc.Name,$assoc.Owner )
Or just (but I don't like it ;) ): 或者只是(但我不喜欢它;)):
Write-host $assoc.Id " - " $assoc.Name " - " $assoc.Owner
#5楼
Try wrapping whatever you want to print out in parenthesis: 尝试用括号将要打印的内容包装起来:
Write-host ($assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner)
Your code is being interpreted as many parameters being passed to Write-Host
. 您的代码被解释为将许多参数传递给Write-Host
。 Wrapping it up inside parenthesis will concatenate the values and then pass the resulting value as a single parameter. 将其包装在括号内将串联这些值,然后将结果值作为单个参数传递。
#6楼
这是另一种替代方法:
Write-host (" {0} - {1} - {2}" -f $assoc.Id, $assoc.Name, $assoc.Owner)
更多推荐
所有评论(0)