How to query Azure virtual machine creation record

Keywords: Excel

Recently, I received a demand. I want to see the record of Azure virtual machine creation, and learn more about what new resources are available on the cloud recently. This is actually a relatively normal demand. With the increasing use of cloud, many enterprises are no longer satisfied with simple cloud use, but more focused on how to use the cloud well. The more core point is that more and more enterprises are closing down Note the cost problem on the cloud, so the rationality of resource use is more and more a focus of enterprises


Returning to the theme, how to implement this requirement in Azure? In fact, VM creation records can be found in the deployment records of resource groups. However, the information collected in this way is scattered, and it is impossible for us to view and sort out each resource group one by one. What's the best way?




In fact, we can directly solve this problem through Azure PowerShell, just write a simple script. First, run the following command to get all log s of Azure in the past three months

    

$logs = Get-AzureRmLog -ResourceProvider Microsoft.Compute -StartTime (Get-Date).AddDays(-90) -Maxrecord 100000



foreach($log in $logs)
{
    if(($log.OperationName.Value -eq 'Microsoft.Compute/virtualMachines/write') -and ($log.SubStatus.Value -eq 'Created'))
    {
        Write-Output "$($log.caller) created vm $($log.Id.split("/")[8])  at $($log.EventTimestamp)  in Resource Group $($log.ResourceGroupName)"
    }

}

    



So you can see the records created by VM!



So what if you want to aggregate this information into Excel? You can use the following code!

[pscustomobject[]]$VMObjects = $null
foreach ($log in $logs) {
        if (($log.OperationName.Value -eq 'Microsoft.Compute/virtualMachines/write') -and ($log.SubStatus.Value -eq 'Created')) {
            Write-Output "$($log.caller) created vm $($log.Id.split("/")[8])  at $($log.EventTimestamp)  in Resource Group $($log.ResourceGroupName)"

            $VMObject = New-Object -TypeName psobject
            $VMObject | Add-Member -MemberType NoteProperty -Name SubscriptionName -Value $SubscriptionName
            $VMObject | Add-Member -MemberType NoteProperty -Name SubscriptionID -Value $SubscriptionID
            $VMObject | Add-Member -MemberType NoteProperty -Name ResourceGroup -Value $log.ResourceGroupName
            $VMObject | Add-Member -MemberType NoteProperty -Name VMName -Value $log.Id.split("/")[8]
            $VMObject | Add-Member -MemberType NoteProperty -Name Time -Value $log.EventTimestamp
            $VMObjects += $VMObject

        }

    }
    
    $OutputPath="C:\vm.csv"
    $VMObjects | Export-Csv -NoTypeInformation -LiteralPath $OutputPath


Finally, this method can only collect log s within 90 days, because the longest time the Azure platform is open to users is 90 days

Posted by etrooper on Fri, 17 Jan 2020 07:34:34 -0800