gpt4 book ai didi

windows - 如何递归文件夹并确定文件夹大小?

转载 作者:可可西里 更新时间:2023-11-01 10:07:56 24 4
gpt4 key购买 nike

我对“Windows PowerShell Tip of the Week”中的脚本稍作修改。这个想法是确定文件夹及其子文件夹的大小:

$startFolder = "C:\Temp\"

$colItems = (Get-ChildItem $startFolder | Measure-Object | Select-Object -ExpandProperty count)
"$startFolder -- " + "{0:N2}" -f ($colItems.sum / 1MB) + " MB"

$colItems = (Get-ChildItem $startFolder -recurse | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object)
foreach ($i in $colItems)
{
$subFolderItems = (Get-ChildItem $i.FullName | Measure-Object -property length -sum)
$i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
}

此脚本运行正常,但对于某些文件夹,我收到一条错误消息:

Measure-Object : Property "length" cannot be found in any object(s) input.
At line:10 char:70
+ $subFolderItems = (Get-ChildItem $i.FullName | Measure-Object <<<< -property length -sum)
+ CategoryInfo : InvalidArgument: (:) [Measure-Object], PSArgumentException
+ FullyQualifiedErrorId : GenericMeasurePropertyNotFound,Microsoft.PowerShell.Commands.MeasureObjectCommand

这个错误的原因是什么,如何优化脚本来克服?

最佳答案

您可以为 Measure-Object 使用 -ErrorAction 参数:

$subFolderItems = (Get-ChildItem $i.FullName | Measure-Object -property length -sum -ErrorAction SilentlyContinue)

或其带有数值的别名 -ea,这对于在交互式实验中快速添加它非常有用:

$subFolderItems = (Get-ChildItem $i.FullName | Measure-Object -property length -sum -ea 0)

不过,在我看来,Technet 上的脚本是非常糟糕的 PowerShell 代码。

作为一种非常快速但肮脏(且缓慢)的解决方案,您还可以使用以下单行代码:

# Find folders
Get-ChildItem -Recurse | Where-Object { $_.PSIsContainer } |
# Find cumulative size of the directories and put it into nice objects
ForEach-Object {
New-Object PSObject -Property @{
Path = $_.FullName
Size = [Math]::Round((Get-ChildItem -Recurse $_.FullName | Measure-Object Length -Sum -ErrorAction SilentlyContinue).Sum / 1MB, 2)
}
} |
# Exclude empty directories
Where-Object { $_.Size -gt 0 } |
# Format nicely
Format-Table -AutoSize

或者实际上作为单行:

gci -r|?{$_.PSIsContainer}|%{New-Object PSObject -p @{Path=$_.FullName;Size=[Math]::Round((gci -r $_.FullName|measure Length -s -ea 0).Sum/1MB,2)}}|?{$_.Size}|ft -a

关于windows - 如何递归文件夹并确定文件夹大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11010035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com