📜  c# azure get vm get cpu usage - C# Code Example

📅  最后修改于: 2022-03-11 14:48:41.256000             🧑  作者: Mango

代码示例1
private void test()
{
    string vmName = "myVM";
    string resourceId = "/subscriptions/{subscriptionId}/resourceGroups/ResourceGroupWest/providers/Microsoft.Compute/virtualMachines/" + vmName;
    var subscriptionId = "mySubscriptionID";
    var clientId = "myClientID";
    var secret = "myKey";
    var tenantId = "myTenantID";
    resourceId = resourceId.Replace("{subscriptionId}", subscriptionId);

    MonitorClient readOnlyClient = AuthenticateWithReadOnlyClient(tenantId, clientId, secret, subscriptionId).Result;

    string queryString = "name.value eq 'CpuPercentage'";
    ODataQuery odataQuery = new ODataQuery(queryString);
    var vals = readOnlyClient.Metrics.List(resourceId, odataQuery );
    foreach (MetricValue v in vals.Value[0].Timeseries[0].Data)
    {
        if (v.Average != null)
        {
            totalAverage += v.Average.Value;
        }
    }
    totalAverage = totalAverage / vals.Value[0].Timeseries[0].Data.Count;
}

private static async Task AuthenticateWithReadOnlyClient(string tenantId, string clientId, string secret, string subscriptionId)
{
    // Build the service credentials and Monitor client            
    var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);            
    var monitorClient = new MonitorClient(serviceCreds);           
    monitorClient.SubscriptionId = subscriptionId;            
    return monitorClient;        
}