You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何用PowerShell快速获取AWS S3存储桶大小?

快速获取AWS S3存储桶大小的PowerShell方案

方法1:正确使用CloudWatch指标(最快,近似值)

你之前用Get-CWMetricsStatistic没拿到结果,大概率是参数配置错误,以下是正确的调用方式:

$bucketName = "your-bucket-name"
$profileName = "your-aws-profile"

# 获取存储桶总大小(包含所有常用存储类型)
$sizeBytes = Get-CWMetricStatistic -Namespace AWS/S3 `
    -MetricName BucketSizeBytes `
    -StartTime (Get-Date).AddHours(-24) `
    -EndTime (Get-Date) `
    -Period 86400 `
    -Statistics Sum `
    -Dimension @(
        @{Name='BucketName'; Value=$bucketName},
        @{Name='StorageType'; Value='StandardStorage'},
        @{Name='StorageType'; Value='StandardIAStorage'},
        @{Name='StorageType'; Value='GlacierStorage'}
        # 按需添加你实际使用的存储类型,比如GlacierInstantRetrievalStorage等
    ) `
    -ProfileName $profileName | Select-Object -ExpandProperty Datapoints | Measure-Object -Sum -Property Sum | Select-Object -ExpandProperty Sum

关键注意点:

  • CloudWatch的S3指标有15分钟延迟,是近似值,但查询速度极快
  • 必须指定StorageType维度,这是之前返回空结果的核心原因
  • 确保你的IAM身份拥有cloudwatch:GetMetricStatistics权限
  • 若只需要特定存储类型的大小,仅保留对应StorageType维度即可

方法2:S3 Inventory(精确值,适合超大桶)

对于5000万+文件的超大规模桶,最高效的精确统计方式是用S3 Inventory:

  1. 在AWS控制台开启目标桶的Inventory配置,设置每日生成CSV格式的对象清单
  2. 等待报告生成后,用PowerShell下载并解析:
$inventoryBucket = "your-inventory-bucket"
$inventoryPrefix = "inventory/report-prefix/"
$profileName = "your-aws-profile"

# 获取最新的Inventory报告文件
$latestInventory = Get-S3Object -BucketName $inventoryBucket -Prefix $inventoryPrefix -ProfileName $profileName | Sort-Object LastModified -Descending | Select-Object -First 1
Copy-S3Object -BucketName $inventoryBucket -Key $latestInventory.Key -LocalFile "inventory.csv" -ProfileName $profileName

# 计算总大小
$totalSize = Import-Csv "inventory.csv" | Measure-Object -Sum -Property Size | Select-Object -ExpandProperty Sum

优势:

  • 无需遍历所有对象,直接读取预生成的报告,速度极快
  • 结果100%精确,还能同步获取文件数量、存储类型等额外信息
  • 一次性配置后可长期复用,适合超大桶的定期统计

方法3:AWS CLI + PowerShell(精确值,中等规模桶)

如果不想等Inventory生成,也可以用AWS CLI的高效分页能力,在PowerShell中调用:

$bucketName = "your-bucket-name"
$profileName = "your-aws-profile"

# 直接返回总字节数
$sizeBytes = aws s3api list-objects-v2 --bucket $bucketName --profile $profileName --query "sum(Contents[].Size)" --output text

# 转换为GB格式输出
$sizeGB = [math]::Round($sizeBytes / 1GB, 2)
Write-Host "桶总大小:$sizeGB GB"

额外技巧:

  • 若需要直接获取人类可读格式的结果,可使用:
aws s3 ls s3://$bucketName --summarize --human-readable --recursive --profile $profileName

为什么原Get-S3Object命令慢?

Get-S3Object需要遍历桶内每一个对象,5000万+文件的场景下,网络IO和本地数据处理都会产生极大开销,完全不适合大规模桶的统计需求。

内容的提问来源于stack exchange,提问作者Vox Over

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:01:03