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

时间:2017-06-16 13:40:29

标签: powershell windows-server-2012-r2 powershell-v5.0

我有以下代码:

$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()

返回错误:

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],我会期待这个,但我不是。发生了什么以及如何检索集合中的项目数?

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:-1)

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

$a.Count

我不了解增加复杂性的必要性,以及.NET / C#方法。你需要提供什么吗?