我正在尝试使用powershell编写脚本来获取文件夹/文件大小,如下所述
$StartFolder = "D:\"
$Output = "C:\Temp\test-d.csv"
Add-Content -Value "Folder Path|Size" -Path $Output
$colItems = (Get-ChildItem $startFolder -Recurse | Measure-Object -Property Length -Sum)
"$StartFolder -- " + "{0:N2}" -f ($colItems.Sum / 1MB) + " MB" # | Out-File $Output
$colItems = (Get-ChildItem $startFolder -Recurse | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object)
foreach ($i in $colItems) {
$subFolderItems = (Get-ChildItem $i.FullName -Recurse | Measure-Object -Property Length -Sum)
$i.FullName + "|" + "{0:N2}" -f ($subFolderItems.Sum / 1MB) + " MB" | Out-File $Output -Append
}
我收到的错误如下所述:
Measure-Object : The property "Length" cannot be found in the input for any objects. At line:12 char:65 + $subFolderItems = (Get-ChildItem $i.FullName -Recurse | Measure-Object - ... + + CategoryInfo : InvalidArgument: (:) [Measure-Object], PSArgumentException + FullyQualifiedErrorId : GenericMeasurePropertyNotFound,Microsoft.PowerShell.Commands.MeasureObjectCommand Measure-Object : The property "Length" cannot be found in the input for any objects. At line:12 char:65 + $subFolderItems = (Get-ChildItem $i.FullName -Recurse | Measure-Object - ... + + CategoryInfo : InvalidArgument: (:) [Measure-Object], PSArgumentException + FullyQualifiedErrorId : GenericMeasurePropertyNotFound,Microsoft.PowerShell.Commands.MeasureObjectCommand
此外,当我定位C:驱动器时,我在某些系统文件上获得“拒绝访问”:
Get-ChildItem : Access to the path 'C:\Windows\System32\LogFiles\WMI\RtBackup' is denied. At line:12 char:28 + $subFolderItems = (Get-ChildItem $i.FullName -Recurse | Measure-Object - ... + + CategoryInfo : PermissionDenied: (C:\Windows\Syst...es\WMI\RtBackup:String) [Get-ChildItem], UnauthorizedAccessException + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
答案 0 :(得分:3)
DirectoryInfo
个对象没有属性Length
,因此您需要将大小计算限制为文件。
$colItems = Get-ChildItem $startFolder -Recurse -Force |
Where-Object { -not $_.PSIsContainer } |
Measure-Object -Property Length -Sum
使用Scripting.FileSystemObject
COM对象可能更容易,因为这将允许您获取具有其内容大小的目录对象。您可能希望使用Export-Csv
将数据导出为CSV。使用calculated properties构建所需的对象。
$fso = New-Object -COM 'Scripting.FileSystemObject'
$folders = @($StartFolder)
$folders += Get-ChildItem $StartFolder -Recurse -Force |
Where-Object { $_.PSIsContainer } |
Select-Object -Expand FullName
$folders |
Select-Object @{n='Path';e={$_}}, @{n='Size';e={$fso.GetFolder($_).Size}} |
Export-Csv $Output -Delimiter '|' -NoType