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

如何在PowerShell数组中添加自定义汇总行?现有实现需优化

PowerShell Azure订阅成本汇总数组优化方案

你当前的代码在收集Azure订阅成本后,直接通过追加字符串和数值的方式添加总和行,会导致数组元素类型混杂,后续处理(如邮件格式化、导出)容易出错,同时数组追加的方式在订阅数量较多时性能较差。以下是优化方案:

原代码存在的问题

  • 使用$report += $x追加元素:PowerShell中数组是固定大小的,每次追加都会创建新数组,订阅数量多的时候会明显降低效率
  • 总和行的添加方式错误:直接追加'-'、'Summe in Euro'和数值,破坏了数组原本的自定义对象结构,导致数组同时包含对象、字符串和数值类型,后续无法统一处理

优化后的代码

$subs = Get-AzSubscription 

$currentBillingPeriod = Get-AzBillingPeriod -Name 202209 #-MaxCount 1
$startDate = $currentBillingPeriod.BillingPeriodStartDate.ToString("dd-MM-yyyy")
Write-Host "currentBillingPeriod startDate : " $startDate
$endDate = $currentBillingPeriod.BillingPeriodEndDate.ToString("dd-MM-yyyy")
Write-Host "currentBillingPeriod endDate : " $endDate

# 使用泛型列表替代普通数组,提升追加性能
$report = [System.Collections.Generic.List[PSObject]]::new()

foreach ($sub in $subs){
    # 创建统一结构的自定义对象
    $costRecord = [PSCustomObject]@{
        'Subscription' = $sub.Name
        'cost in Euro' = 0
        'Period' = $currentBillingPeriod.Name
    }

    # 切换订阅上下文并获取成本总和
    $null = Set-AzContext -SubscriptionName $sub.Name
    $currentCost = Get-AzConsumptionUsageDetail -StartDate $startDate -EndDate $endDate | 
                   Measure-Object -Property PretaxCost -Sum
    $costRecord.'cost in Euro' = [math]::Round($currentCost.Sum, 2)

    $report.Add($costRecord)
    Write-Host "Current Cost of Subscription :" $sub.Name $currentCost.Sum
}

# 创建结构一致的总和记录
$totalRecord = [PSCustomObject]@{
    'Subscription' = '总和(Summe in Euro)'
    'cost in Euro' = [math]::Round(($report | Measure-Object 'cost in Euro' -Sum).Sum, 2)
    'Period' = $currentBillingPeriod.Name
}

# 将总和记录添加到报告列表
$report.Add($totalRecord)

# 输出完整报告
$report
$mailreport = $report
$mailreport

优化关键点

  1. 使用泛型列表:[System.Collections.Generic.List[PSObject]]支持高效的元素追加操作,避免了普通数组每次追加时的内存重新分配问题
  2. 保持结构一致性:总和行同样创建为和其他记录结构一致的PSCustomObject,确保整个数组的元素类型统一,后续无论是输出、导出还是邮件格式化都能正常处理
  3. 简化对象创建:用[PSCustomObject]@{}直接创建自定义对象,比"" | Select更直观高效
  4. 隐藏上下文切换输出:用$null = Set-AzContext...避免不必要的输出干扰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:01:31