PowerShell中如何合并$metrics的时间戳与值生成可导出CSV的变量
需求说明
现有PowerShell变量$metrics为AWS CloudWatch接口返回的指标数据集合,结构如下:
PS C:\Windows\system32> $metrics Id : cpuUtil01 Label : CPUUtilization Messages : {} StatusCode : Complete Timestamps : {11/27/2021 7:00:00 PM, 11/27/2021 7:05:00 PM, 11/27/2021 7:10:00 PM, 11/27/2021 7:15:00 PM...} Values : {51.22, 31.3833333333333, 31.4116666666667, 31.5283333333333...}
需要提取$metrics.Timestamps和$metrics.Values两个一一对应的属性,合并为可直接导出CSV的结构化变量,用于生成Excel折线图。
补充变量类型信息
PS C:\Windows\system32> $metrics.GeTtype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True List`1 System.Object PS C:\Windows\system32> $metrics.Values.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array PS C:\Windows\system32> $metrics | Get-Member TypeName: Amazon.CloudWatch.Model.MetricDataResult Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() Id Property string Id {get;set;} Label Property string Label {get;set;} Messages Property System.Collections.Generic.List[Amazon.CloudWatch.Model.MessageData] Messages {get;set;} StatusCode Property Amazon.CloudWatch.StatusCode StatusCode {get;set;} Timestamps Property System.Collections.Generic.List[datetime] Timestamps {get;set;} Values Property System.Collections.Generic.List[double] Values {get;set;}
实现代码
由于Timestamps和Values两个集合是严格按顺序一一对应的,直接按索引遍历配对即可:
# 合并两个属性生成目标变量 $output = for ($i = 0; $i -lt $metrics.Timestamps.Count; $i++) { [PSCustomObject][ordered]@{ TimeStampUTC = $metrics.Timestamps[$i] Values = $metrics.Values[$i] } } # 导出为CSV文件,-UseCulture参数保证和本地Excel的分隔符兼容 $output | Export-Csv -Path "C:\CPU_Utilization_Metrics.csv" -NoTypeInformation -UseCulture
输出效果
生成的$output变量结构符合要求:
TimeStampUTC Values ------------ ------ 11/27/2021 7:00:00 PM 51.22 11/27/2021 7:05:00 PM 31.3833333333333 11/27/2021 7:10:00 PM 31.4116666666667 11/27/2021 7:15:00 PM 31.5283333333333 ...
内容的提问来源于stack exchange,提问作者Rugbyball
相关产品推荐
相关产品推荐

