如何在循环中使用PowerShell连接字符串?

时间:2013-12-05 17:14:19

标签: string loops powershell foreach concatenation

命令

Get-VM | Where {$_.PowerState -eq "PoweredOn"} | Select Name,VMHost | Where {$_ -match "abc" -or $_ -match "def"} | foreach{$_.Name} | Out-File output.txt

将列表写入output.txt,其中只有列名称将以以下形式打印:

a
b
c
...

现在我想要实现的是在某种循环中将,xxx附加到每一行,以便我得到以下内容:

a,xxx
b,xxx
c,xxx
...

我试图追加字符串,但这似乎不起作用:

Get-VM | Where {$_.PowerState -eq "PoweredOn"} | Select Name,VMHost | Where {$_ -match "abc" -or $_ -match "def"} | foreach{$_.Name} | Out-File output.txt | Add-Content output.txt ",xxx"

我真的不熟悉PowerShell,但我找不到连接,xxx的方法。

在我的情况下,必须在循环中进行连接,而不是之后的文件操作。

1 个答案:

答案 0 :(得分:8)

而不是foreach { $_.Name },请写foreach { "$($_.Name),xxx" }

相关问题