How to get Azure VM activity logs using PowerShell?

To get the Azure VM activity logs with PowerShell, we need to use the Get-AzLog command. Before running, AZ commands make sure that you are connected to the Azure Account using (ConnectAzAccount) and the subscription (Set-AzContext).

We have the below TestVM, we need to retrieve activity logs and we need its resource id. We will get the resource ID using,

PS C:\> $vm = Get-AzVM -VMName TestVM
PS C:\> $vm.Id

We need to use this ID in the Get-AzLog command to retrieve the activity logs.

PS C:\> Get-AzLog -ResourceId $vm.Id

It will provide all the azure events for that specific resource group and you can see the number of properties. If we need to retrieve the only properties which are shown in the azure activity log on the portal, you can use the below command.

(Get-AzLog -ResourceId $vm.Id) | Select
@{N='Message';E={$_.OperationName.LocalizedValue}}, Level, Caller, EventTimestamp |
ft -AutoSize

You can filter the event with a specific level. For example, to filter only warning logs,

(Get-AzLog -ResourceId $vm.Id) | where{$_.Level -eq "Warning"} | Select
@{N='Message';E={$_.OperationName.LocalizedValue}},Level, Caller, EventTimestamp

You can add the start and end times as shown below.

Get-AzLog -ResourceId $vm.Id -StartTime 2021-03-01 -EndTime
2021-05-25 -MaxRecord 20 | `
   Select @{N='VMName';E={$vm.Name}},ResourceGroupName,
Caller, EventTimestamp

Updated on: 31-Aug-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started