我很困惑我在 List 的 ForEach 方法语法中做错了什么?
PS D:\ntt> $nicInfo.IpConfigurations.Count
2
PS D:\ntt> $nicInfo.IpConfigurations[0]
PrivateIpAddressVersion Name Primary PrivateIpAddress PrivateIpAllocationMethod Subnet Name PublicIpAddress Name ProvisioningState
----------------------- ---- ------- ---------------- ------------------------- ----------- -------------------- -----------------
IPv4 ipconfig1 True 10.233.0.4 Dynamic Succeeded
PS D:\ntt> $nicInfo.IpConfigurations.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True List`1 System.Object
PS D:\ntt> $nicInfo.IpConfigurations.ForEach({$_})
PS D:\ntt>
问题是PowerShell自己的.ForEach()
收集方法在这种情况下被
List<T>
类型自己的.ForEach()
方法抢占:
.ForEach({ ... })
:
$_
定义为脚本块参数 (
{ ... }
)的输入对象
List<T>
的
.ForEach({ ... })
将脚本块转换为Action<T>
委托,它具有以下含义/限制:
委托不知道脚本块内的$_
$args[0]
访问的单个参数。 脚本块的
输出 被忽略,因为根据定义,Action<T>
委托没有返回值。 虽然您可以在脚本块中使用
Write-Host
输出不能以编程方式使用,因为它绕过 PowerShell 的输出流,因此既不能被捕获也不能重定向。
:
.ForEach()
的脚本块不需要产生任何输出,所需要做的就是在脚本块中使用
$args[0]
代替 $_
,尽管您仍然可以选择使用其中之一为了避免混淆,请使用下面的其他解决方法。
,最简单的解决方案是将List<T>
实例转换为
数组,首先使用
.ToArray()
,
.ForEach()
按预期工作;一个简化的例子: $list = [System.Collections.Generic.List[object]] ('foo', 'bar')
$list.ToArray().ForEach({ $_ + '!' }) # Note the .ToArray() call.
上面产生了
'foo!', 'bar!'
,正如预期的那样。
$nicInfo.IpConfigurations | ForEach-Object {
$ipConfiguration = $_
write-Output $ipConfiguration
# do more stuff with this $ipConfiguration
}