How to query Azure virtual machine creation records
Recently received a demand, want to take a look at the Azure virtual machine creation records, detailed understanding of the recent cloud what new resources, this is actually a relatively normal demand, as the cloud is more and more widely used, many enterprises are no longer satisfied with the simple use of the cloud, but more focused on how to make good use of the cloud, a more core point is that more and more enterprises begin to pay attention to the cloud cost problem Therefore, the rationality of the use of resources is more and more a focus of enterprises.
To return to the topic, then how to achieve this requirement in Azure? in fact, the creation record of VM can be found in the deployment record of the resource group, but the information collected in this way is very fragmented, and it is impossible for us to check and sort out this information one by one, so what is the good way?
In fact, we can solve this problem directly through Azure's PowerShell. We only need to write a simple script. First, run the following command to get all the log 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 ResourceGroup $($log.ResourceGroupName)"}}
So you can see the record created by VM!
What if you want to aggregate this information into Excel? You can use the following code!
[pscustomobject []] $VMObjects = $nullforeach ($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 ResourceGroup $($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 logs within 90 days, because the longest log open to users on the Azure platform is 90 days.