Powershell 针对集合的每个成员而不是集合进行评估

Powershell evaluating against each member of collection rather than collection

我有以下代码:

$a = gci .\Areas -Recurse
($a[0].EnumerateFileSystemInfos()).Count

这是它的输出

PS C:\> ($a[0].EnumerateFileSystemInfos()).Count
1
1
1
1
1
1

为什么?当我运行gm -InputObject $a[0]时,我清楚地看到返回了一个集合。

EnumerateFileSystemInfos  Method         System.Collections.Generic.IEnumerable[System.IO.FileSystemInfo] EnumerateF...

为什么要针对集合的每个成员而不是集合本身评估 .Count?另外值得注意的是

($a[0].EnumerateFileSystemInfos()).Count()

returns一个错误:

Method invocation failed because [System.IO.FileInfo] does not contain a method named 'Count'.
At line:1 char:1
+ ($a[0].EnumerateFileSystemInfos()).Count()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

如果我针对 $a[0][0] 调用它,这是我期望的结果,但我没有。发生了什么事以及如何检索集合中的项目数?

EnumerateFileSystemInfos()returns一个IEnumerable,更准确地说,一个System.IO.FileSystemEnumerableIterator'1,因此每次查询它returns一个对象。当您将输出传输到 Out-Default 时,该 cmdlet 会检查 IEnumerable 是否有更多数据,如果是,则再次查询。这就是为什么你得到一个 1 序列的原因,因为可枚举后面的每个对象都是单个对象而不是数组。

您应该使用 GetFileSystemInfos() 来获得正确的计数,它 returns 是一个数组。

获取集合中的项目数$a:

$a.Count

我不明白需要增加复杂性以及 .NET/C# 方法。这里面有什么是你需要的吗?