You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理PowerShell中Select-String返回System.Object[]的问题

解决方法

你遇到的问题是因为Select-String返回的是MatchInfo对象数组,当直接将其插入字符串模板时,PowerShell会调用数组的默认ToString()方法,结果就是System.Object[]。要展开这些匹配项,只需提取每个匹配的具体行内容,再用换行符连接即可,同时兼容单行匹配的情况。

修改后的代码如下:

gci -include *.vb,*.config, *.frm, *.dsr, *.cls, *.bas, *.iss, *.h, *.cs, *.resx, *.json, *.yml, *.xaml, *.wxs, *.wxi, *.wxl, *.cpp -recurse | % {
@'
File name - {0}
{1}
.....................
'@ -f $_.FullName, ((get-content $_.FullName | select-string -pattern '^.*\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.*$') | ForEach-Object { $_.Line }) -join "`n"
} | out-file -filepath .\ips.txt

关键修改说明:

  • 通过ForEach-Object { $_.Line }提取每个匹配结果的具体行文本,避免直接输出对象本身
  • 用-join "n"`将所有匹配行用换行符连接,无论匹配结果是单行还是多行,都会输出为可读的字符串形式

如果需要更详细的信息(比如匹配的行号),可以把$_.Line替换为"行号: $($_.LineNumber) - $($_.Line)",这样输出会包含行号,方便定位内容。

内容的提问来源于stack exchange,提问作者Travis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 21:12:09