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

为何(ConvertFrom-Yaml $yaml).anArray.ForEach({ $_ })返回$null?

问题原因与解决方案

你遇到的核心问题是调用了两种完全不同的.ForEach()方法:

  1. PowerShell数组的扩展.ForEach()
    当你对System.Array(比如@(1,2,3))调用.ForEach({ ... })时,用的是PowerShell为数组类型专门提供的扩展方法。这个方法会遍历集合、执行脚本块逻辑,并且返回处理后的结果集合,所以你可以链式调用它。

  2. .NET原生List<T>的.ForEach()
    ConvertFrom-Yaml返回的List1是.NET框架原生的List泛型集合,它自带的.ForEach()方法是.NET的原生方法:List.ForEach(Action)。这个方法的设计初衷是**仅执行传入的动作(比如修改元素、打印内容),但不返回任何值**,因此在PowerShell中调用它会得到$null`。


验证方法

你可以通过Get-Member查看两种方法的差异:

# 查看List<T>的ForEach方法
(ConvertFrom-Yaml $yaml).anArray | Get-Member -Name ForEach

# 查看数组的ForEach方法
@(1,2,3) | Get-Member -Name ForEach

前者的返回类型是void,后者则会返回处理后的对象数组。


解决方案

有三种常用方式让List<T>也能实现类似数组的.ForEach()返回效果:

1. 转为PowerShell数组

通过@()强制包裹或调用ToArray()方法,将List<T>转为System.Array,之后就能使用PowerShell的扩展.ForEach():

# 方式1:@()强制转换
@((ConvertFrom-Yaml $yaml).anArray).ForEach({ $_ })

# 方式2:调用List<T>的ToArray()方法
(ConvertFrom-Yaml $yaml).anArray.ToArray().ForEach({ $_ })

2. 使用ForEach-Object cmdlet

这是PowerShell中通用的遍历处理方式,适用于所有集合类型:

(ConvertFrom-Yaml $yaml).anArray | ForEach-Object { $_ }

3. 直接利用PowerShell的集合枚举

如果只是需要输出集合元素,直接输出List<T>对象即可,PowerShell会自动枚举元素:

(ConvertFrom-Yaml $yaml).anArray

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 08:47:21