Azure自动化账户脚本修改:获取文件共享配额与已用容量
Azure 文件共享已用容量问题解决方案
一、PowerShell脚本修改(支持已用容量计算)
以下是适配Azure自动化账户的脚本,可递归遍历文件共享内所有文件计算精确已用容量,同时获取共享列表与配额:
# 导入Az存储模块(Azure自动化账户需预先导入Az.Storage) Import-Module Az.Storage # 配置目标存储账户信息 $storageAccountName = "你的存储账户名" $resourceGroupName = "你的资源组名" # 获取存储账户上下文 $storageAccount = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName $ctx = $storageAccount.Context # 获取存储账户下所有文件共享 $fileShares = Get-AzStorageShare -Context $ctx # 遍历共享计算数据并输出结果 $results = foreach ($share in $fileShares) { # 获取共享配额(GiB) $quotaGiB = $share.QuotaGiB # 递归遍历所有文件计算总大小 $totalSizeBytes = 0 # 处理根目录文件 $rootFiles = Get-AzStorageFile -ShareName $share.Name -Context $ctx | Where-Object { $_.GetType().Name -eq "CloudFile" } foreach ($file in $rootFiles) { $totalSizeBytes += $file.Properties.Length } # 递归处理子目录的函数 function Get-RecursiveFileSize { param( [Parameter(Mandatory=$true)] [Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageFileDirectory]$Directory, [Parameter(Mandatory=$true)] [long]$CurrentTotal ) $subFiles = Get-AzStorageFile -Directory $Directory | Where-Object { $_.GetType().Name -eq "CloudFile" } foreach ($file in $subFiles) { $CurrentTotal += $file.Properties.Length } $subDirs = Get-AzStorageFile -Directory $Directory | Where-Object { $_.GetType().Name -eq "CloudFileDirectory" } foreach ($dir in $subDirs) { $CurrentTotal = Get-RecursiveFileSize -Directory $dir -CurrentTotal $CurrentTotal } return $CurrentTotal } # 处理根目录下的子目录 $rootDirs = Get-AzStorageFile -ShareName $share.Name -Context $ctx | Where-Object { $_.GetType().Name -eq "CloudFileDirectory" } foreach ($dir in $rootDirs) { $totalSizeBytes = Get-RecursiveFileSize -Directory $dir -CurrentTotal $totalSizeBytes } # 转换为GiB并保留两位小数 $usedGiB = [math]::Round($totalSizeBytes / 1GB, 2) # 构造结果对象 [PSCustomObject]@{ 共享名称 = $share.Name 总配额(GiB) = $quotaGiB 已用容量(GiB) = $usedGiB } } # 输出最终结果 $results
注意:需为Azure自动化账户分配目标存储账户的Storage File Data Contributor权限,避免权限不足导致遍历失败。
二、存储账户API的限制说明
目前Azure存储REST API(包括Az模块、Azure CLI底层调用的接口)没有直接返回文件共享已用容量的端点,核心原因是服务端未缓存该统计值,不会主动实时计算并存储。
通过遍历文件获取容量时,需注意两个限制:
- 请求速率限制:标准存储账户每秒最多支持2万次请求,若共享内文件量极大,遍历过程可能触发限流,需添加重试逻辑或通过
-MaxCount参数分页处理请求。 - 性能开销:文件数量越多,遍历计算耗时越长,可能拉长自动化作业的执行时间。
三、是否需要启用额外指标
无需额外启用指标,Azure Monitor默认会收集存储账户的UsedCapacity指标,支持按单个文件共享维度筛选。
两种方案对比
- Monitor指标方案:无需遍历文件,效率极高,但数据存在5-15分钟延迟,属于近似值,适合非实时场景。可通过以下代码获取:
Import-Module Az.Monitor $startTime = (Get-Date).AddHours(-1) $endTime = Get-Date # 获取指定存储账户下文件共享的已用容量指标 $metrics = Get-AzMetric -ResourceId $storageAccount.Id -MetricName "UsedCapacity" -StartTime $startTime -EndTime $endTime -AggregationType Average -Dimension "ShareName" # 解析输出结果 foreach ($metric in $metrics.Data) { [PSCustomObject]@{ 共享名称 = $metric.Dimensions[0].Value 已用容量(GiB) = [math]::Round($metric.Average / 1GB, 2) } }
- 遍历文件方案:数据精确实时,但效率依赖文件数量,适合需要精确值的场景。
内容的提问来源于stack exchange,提问作者Michał Picheta
相关产品推荐
相关产品推荐

