Azure Automation. PSMetric to integer

207 Views Asked by At

I am trying to create an Azure Automation workbook that queries a resource for some metrics, and does some scaling up/down based in that metric. I have no idea how I can convert a PSMetricData to integer in order to do comparisons on it. My code at the moment is

    $MonitorParameters = @{
    ResourceId = "abcde....." 
    TimeGrain = [TimeSpan]::Parse("00:05:00")
    MetricNames = "cpu_percent"
}

$MetricValues = Get-AzMetric @MonitorParameters -DetailedOutput
$Last = $MetricValues.Data[0]

Write-Output $Last

And my output is

Microsoft.Azure.Commands.Insights.OutputClasses.PSMetricValue

I am looking in general for something like: "If the last 5 mins has a cpu_percentage > 70%", then scale up..

2

There are 2 best solutions below

8
On BEST ANSWER

Just use Write-Output $Last.Average instead of Write-Output $Last, then you will get the specific value.

And you should note the newest value got from the command Get-AzMetric is before the last one hour, e.g. if now is 2:37:00 AM, then the newest one is 1:38:00 AM, you could not get the last 5 mins value, the TimeGrain = [TimeSpan]::Parse("00:05:00") just means get the value every five mins.

Update:

It should work, I create a new elastic pool and test it, it is 0.

My script in the runbook:

$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         

    Connect-AzAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}

    $MonitorParameters = @{
    ResourceId = "/subscriptions/xxxxx/resourceGroups/xxxx/providers/Microsoft.Sql/servers/joyserver1/elasticPools/joypool" 
    TimeGrain = [TimeSpan]::Parse("00:05:00")
    MetricNames = "cpu_percent"
}

$MetricValues = Get-AzMetric @MonitorParameters -DetailedOutput
$Last = $MetricValues.Data[0]

Write-Output $Last

enter image description here

0
On

The issue is that I was creating a powershell workflow, not a native powershell script. The script from @Joy Wang above now works as described