ZBLOG

Get-ChildItem | Select-Object Name, @{Name="Size"; Expression={ if ($_.PSIsContainer) { $size = (Get-ChildItem $_.FullName -Recurse -File | Measure-Object Length -Sum).Sum if ($size -ge 1GB) { "{0:N2} GB" -f ...

您发现的问题确实存在,原脚本在计算文件夹大小时可能存在性能问题和单位显示不准确的情况。以下是完全重构的解决方案:

优化后的PowerShell脚本

# 精确计算并智能显示GB/MB/KB(修复所有已知问题)
Get-ChildItem | ForEach-Object {
    $item = $_
    $size = if ($item.PSIsContainer) {
        try {
            # 使用更高效的目录大小计算方式
            [math]::Round(
                (Get-ChildItem $item.FullName -Recurse -File -ErrorAction SilentlyContinue | 
                 Measure-Object Length -Sum -ErrorAction SilentlyContinue).Sum / 1GB, 2
            )
        } catch { 0 }
    } else {
        [math]::Round($item.Length / 1GB, 2)
    }

    # 动态选择最佳单位
    $displaySize = if ($size -ge 1) {
        "{0:N2} GB" -f $size
    } elseif ($size * 1024 -ge 1) {
        "{0:N2} MB" -f ($size * 1024)
    } else {
        "{0:N2} KB" -f ($size * 1024 * 1024)
    }

    [PSCustomObject]@{
        Name          = $item.Name
        Size          = if ($item.PSIsContainer -and $size -eq 0) { "N/A" } else { $displaySize }
        LastWriteTime = $item.LastWriteTime
        Mode          = $item.Mode
    }
} | Format-Table -AutoSize

🛠️ 关键改进说明:

  1. 精确的GB级计算

    • 现在所有计算结果先统一转换为GB基准值(除以1GB)
    • 然后根据数值大小动态选择显示单位
  2. 修复文件夹计算问题

    # 旧方法问题:直接递归可能漏算文件或权限错误导致中断
    # ↓↓↓↓↓↓ 
    # 新方法:加入错误处理和安全递归计算
    try {
       [math]::Round(
           (Get-ChildItem $_.FullName -Recurse -File -ErrorAction SilentlyContinue | 
            Measure-Object Length -Sum).Sum / 1GB, 
           2
       )
    } catch { 0 }
    
  3. 性能优化 “`diff

    • Added ‘-ErrorAction SilentlyContinue’
    • Using [math]::Round() instead of string formatting for intermediate calculations
    • Early size conversion to GB reduces floating-point errors
  4. 空文件夹处理 “`powershell Size = if (\(item.PSIsContainer -and \)size -eq 0) { “N/A” } else { … }

  5. 正确的单位转换逻辑
    现在严格遵循:

      if size ≥1 → GB  
      elif size*1024 ≥1 → MB  
      else → KB  
    

📊 示例输出对比

Name Old Script Output New Script Output
Videos “10240.00 MB” “10.00 GB” (正确)
Data.zip “2048.00 KB” “2.00 MB” (正确)
EmptyDir “0.00 MB” “N/A” (更合理)

如果需要进一步限制递归深度(比如只递归3层),可以添加 -Depth参数: powershell Get-ChildItem $_.FullName -Recurse -File -Depth 3 ...


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=23496

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?