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

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

将只打印“Name”列的列表写入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个回答

9

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接