0

I have a list of instanceIds that I want to use as input into get-cwmetricstatistic in order to output a list of summary cloudwatch metrics. I have the code to obtain the list of instanceIds and I have the code to pull back summary stats for a single instanceId. I am struggling to build the dimension within the foreach-object so that the instanceIDs are passed correctly. Please see example code below...

I know that this works to get InstanceIds:

$instances = Get-EC2Instance -AccessKey $AccessKey -Region us-east-1 -SecretKey $SecretKey -SessionToken $SessionToken | 
Select-Object -ExpandProperty Instances | 
Select-Object InstanceId 

And I know that this works to get summary statistics for a single instanceID:

$dimension = New-Object Amazon.CloudWatch.Model.Dimension
$dimension.set_Name("InstanceId")
$dimension.set_Value("i-xxxxxxxxxxxxxx")

$data = Get-CWMetricStatistic -AccessKey $AccessKey -Dimension $dimension -MetricName CPUUtilization -Namespace AWS/EC2 -Period 86400 -Region us-east-1 -SecretKey $SecretKey -SessionToken $SessionToken -Statistic Average -UtcEndTime 2019-09-28T04:00:00Z -UtcStartTime 2019-09-22T04:00:00Z 
 foreach($datapoint in $data.Datapoints){
    Write-Host $dimension.Value $datapoint.Timestamp " " $datapoint.Average 
}

Here is the code that attempts to loop through the list of instanceIds that does not work:

$instances = Get-EC2Instance -AccessKey $AccessKey -Region us-east-1 -SecretKey $SecretKey -SessionToken $SessionToken | 
Select-Object -ExpandProperty Instances | 
Select-Object InstanceId |

ForEach-Object  {
$dimension = New-Object Amazon.CloudWatch.Model.Dimension
$dimension.set_Name("InstanceId")
$dimension.set_Value($instanceId)

$data = Get-CWMetricStatistic -AccessKey $AccessKey -Dimension $dimension -MetricName CPUUtilization -Namespace AWS/EC2 -Period 86400 -Region us-east-1 -SecretKey $SecretKey -SessionToken $SessionToken -Statistic Average -UtcEndTime 2019-09-28T04:00:00Z -UtcStartTime 2019-09-22T04:00:00Z 
 foreach($datapoint in $data.Datapoints){
    Write-Host $dimension.Value $datapoint.Timestamp " " $datapoint.Average 
}
}
Mike
  • 85
  • 8

1 Answers1

2

Solution:

$instances = Get-EC2Instance -AccessKey $AccessKey -Region us-east-1 -SecretKey $SecretKey -SessionToken $SessionToken | 
Select-Object -ExpandProperty Instances | 

ForEach-Object  {
$dimension = New-Object Amazon.CloudWatch.Model.Dimension
$dimension.Set_Name("InstanceId")
$dimension.Set_Value($_.InstanceId)

$data = Get-CWMetricStatistic -AccessKey $AccessKey -Dimension $dimension -MetricName CPUUtilization -Namespace AWS/EC2 -Period 86400 -Region us-east-1 -SecretKey $SecretKey -SessionToken $SessionToken -Statistic Average -UtcEndTime 2019-09-28T04:00:00Z -UtcStartTime 2019-09-20T04:00:00Z 

foreach($datapoint in $data.Datapoints){
    Write-Host $dimension.Value $datapoint.Timestamp "CPUUtilization-Average" $datapoint.Average
}
} 
Mike
  • 85
  • 8