首页 > 解决方案 > 在 Powershell 中,为什么查找所有目录名称比将所有文件大小相加要慢得多?

问题描述

我对这些命令中的一个与另一个相比慢了多少感到困惑。

此命令通过递归查找 C:\ 中每个子文件夹的大小来查找 C:\ 驱动器的大小

$len = 0
gci -path C:\ -recurse -force  -ErrorAction SilentlyContinue | % { $len += $_.length}

此命令通过递归查看 C:\ 驱动器上的每个文件夹来查找 C:\ 驱动器上每个文件夹的名称

$result = gci -path C:\ –recurse -force -directory -ErrorAction SilentlyContinue | %{$_.fullName}

为什么第一个比第二个快那么多?文件夹大小是否有某种缓存?这仅仅是字符串操作比整数操作慢几个数量级的问题吗?

标签: performancepowershellget-childitem

解决方案


注意:正如您所写的第一个命令会发出一堆错误消息,我取消了该命令,因为它运行了几分钟!尽管目录具有长度属性,但它是完整目录路径的长度,而不是目录的大小(以字节为单位)。

The property 'length' cannot be found on this object. Verify that the property 
exists.
At line:2 char:68
+ ... ecurse -force  -ErrorAction SilentlyContinue | % { $len += $_.length}
+                                                        ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], PropertyNotFoundException
    + FullyQualifiedErrorId : PropertyNotFoundStrict

所以我添加了 -File 开关参数。

PS> $len = 0
Measure-Command -Expression {
  gci -path C:\ -File -recurse -force  -ErrorAction SilentlyContinue | % { $len += $_.length}}

TotalSeconds      : 58.5945269

PS> $len = 0
Measure-Command -Expression {
  $x = gci -path C:\ -File -recurse -force  -ErrorAction SilentlyContinue 
  ForEach ($File in $x) { $Len += $file.length}
}

TotalSeconds      : 48.99365

正如您所看到的,使用 Pipe 比保存到变量(在这种情况下为数组)然后从那里进行处理要慢得多。我编辑了 Measure-Command 输出的冗余信息

在第二个命令中,您不只处理文件目录(-Directory),并且您不计算大小,从而使其更快。如您所见,此命令仅返回目录路径的字符串数组。(为简洁起见再次编辑)。

PS> $result.count
118148

PS> $result[0] | gm

   TypeName: System.Stri

Name             MemberType            Definition                              
----             ----------            ----------                              
Chars            ParameterizedProperty char Chars(int index) {get;}            
Length           Property              int Length {get;}                       

PS> $result[0].Length
14

PS> $result[0]
C:\$GetCurrent

高温高压


推荐阅读