我注意到,在对数组对象运行ForEach并将输出捕获到新变量时,新变量不是System.array类型:
PS D:\Playground> $Arr = 1, 2, 3
PS D:\Playground> $Arr2 = $Arr.ForEach({$_})
PS D:\Playground> $Arr2.Gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Collection`1 System.Object相反,它是Collection'1类型的。
这是什么类型的?它等同于数组吗?
顺便说一句,这与ForEach-Object不一样
PS D:\Playground> $Arr3 = $($Arr | ForEach-Object { $_ })
PS D:\Playground> $Arr3.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array发布于 2021-12-30 18:46:38
让我在耶伦·莫斯特的精彩评论的基础上再接再厉:
.Where()、返回 [System.Collections.ObjectModel.Collection[psobject]]集合实例,而不是常规PowerShell数组([object[]])。- Unlike the related [`ForEach-Object`](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/foreach-object) / [`Where-Object`](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/where-object) _cmdlets_, **these methods** _**always**_ **return a** _**collection**_**, even with only a** _**single**_ **object**:.ForEach()方法:# Collection结果,即使使用单个对象。@(1).ForEach({ $_ }).GetType().Name # -> Collection`1 `1# ForEach- object:#单个输出对象:接收为-is。(@(1) ForEach { $_ }).GetType().Name # -> Int32 #两个或更多输出对象:数组结果(如果在表达式中捕获/使用) (1,2 ForEach { $_ }).GetType().Name # -> Object[]
- Note: These methods are examples of [intrinsic members](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Intrinsic_Members), i.e. properties and methods **PowerShell exposes on** _**all**_ **objects, irrespective of their type** (_unless_ a _type-native_ member of the same name exists, which takes precedence).[System.Collections.Generic.IList[psobject]]接口):- Its elements are _enumerated_ in the pipeline, just as an array's elements are.
- _Positional indexing_ (e.g. `[0]`) is supported, just as with arrays.
- _**Unlike**_ **an array, however**:
- It is _resizable_; that is, its instances allow you to add (`.Add()`) and remove (`.Remove()`) elements.
- Its element type is [`[psobject]`](https://learn.microsoft.com/en-US/dotnet/api/System.Management.Automation.PSObject) (not [`[object]`](https://learn.microsoft.com/en-US/dotnet/api/System.Object)), the _usually_ invisible _helper type_ capable of wrapping any .NET object, which PowerShell employs (largely) behind the scenes.
- Typically, this difference won't matter, but - unfortunately - there are edge cases where it does - see [GitHub issue #5579](https://github.com/PowerShell/PowerShell/issues/5579)..ForEach() method 与 ForEach-Object cmdlet
注意:下面的内容类似于.Where()和Where-Object。
ForEach-Object,以便从PowerShell管道的流行为中获益(在接收输入时,一个接一个地处理,无需预先收集输入);例如:
获取- -Name *.txt| ForEach对象{ "$_“}.ForEach();例如:
('foo.txt','bar.txt').ForEach({ "$_“})不过,请注意上面讨论的单对象行为和输出集合类型的差异。
有关.ForEach()、ForEach-Object、以及成员访问枚举的详细并列,请参见.ForEach()。
https://stackoverflow.com/questions/70533327
复制相似问题