如何在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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值