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

PowerShell中如何对数组内每个字符串拆分后得到嵌套数组?

PowerShell 保留-split后的嵌套数组结构问题

你遇到的问题是PowerShell管道的自动枚举特性导致的:当你在ForEach-Object的脚本块中输出-split返回的数组时,PowerShell会自动把数组中的每个元素单独送入管道,最终所有元素被合并成一个一维数组。

要保留嵌套数组结构,只需要用**逗号运算符,**把每个-split的结果包装成单元素数组,阻止管道展开内部数组:

$Strings = @("a b c", "d e f")
$Sep = " "
$nestedResult = $Strings | ForEach-Object { , ($_ -split $Sep) }

验证结果:

  • $nestedResult[0] 会返回拆分后的第一个数组:a b c
  • $nestedResult[1] 会返回拆分后的第二个数组:d e f

另外也可以用传统的foreach循环实现,适合需要更复杂逻辑的场景:

$nestedArray = @()
foreach ($str in $Strings) {
    $nestedArray += , ($str -split $Sep)
}

注意:+=操作数组会频繁创建新数组,数据量较大时建议用System.Collections.ArrayList来提升性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 11:26:07