Measure-Object:在任何对象的输入中都找不到属性"length"

eri*_*121 6 powershell

我正在创建一个菜单,其中一个选项是报告指定文件夹的文件夹大小并将其显示给用户.我输入文件夹名称后

cls
$Path = Read-Host -Prompt 'Please enter the folder name: '

$FolderItems = (Get-ChildItem $Path -recurse | Measure-Object -property length -sum)      

$FolderSize = "{0:N2}" -f ($FolderItems.sum / 1MB) + " MB"
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Measure-Object : The property "length" cannot be found in the input for any objects.
At C:\Users\Erik\Desktop\powershell script.ps1:53 char:48
+ ... (Get-ChildItem $Path -recurse | Measure-Object -property length -sum)
+                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Measure-Object], PSArgumentException
    + FullyQualifiedErrorId : GenericMeasurePropertyNotFound,Microsoft.PowerShell.Commands. 
   MeasureObjectCommand
Run Code Online (Sandbox Code Playgroud)

Fro*_* F. 7

文件夹中没有文件,因此您只能获得DirectoryInfo没有length-property的-objects .您可以通过以下方式过滤文件来避免这种情况:

(Get-ChildItem $Path -Recurse | Where-Object { -not $_.PSIsContainer } | Measure-Object -property length -sum) 
Run Code Online (Sandbox Code Playgroud)

或PS 3.0+

(Get-ChildItem $Path -Recurse -File | Measure-Object -property length -sum)
Run Code Online (Sandbox Code Playgroud)