本文翻译自: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)
GitHub 加速计划 / po / PowerShell
44.28 K
7.17 K
下载
PowerShell/PowerShell: PowerShell 是由微软开发的命令行外壳程序和脚本环境,支持任务自动化和配置管理。它包含了丰富的.NET框架功能,适用于Windows和多个非Windows平台,提供了一种强大而灵活的方式来控制和自动执行系统管理任务。
最近提交(Master分支:3 个月前 )
a1774fd9 3 个月前
5ad1f1d2 3 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐