Get Azure logs using PowerShell script

Today I wanted to show you one of the method for getting Azure logs. In this case I was looking for information about start and stop action.

Azure logs

To connect to Azure resources and be able to check logs you need few things:

  • Azure Credentials
  • Environment
  • TenantID
  • Subscription
  • Resource Group Name

Below you can find example for converting your password to secure string and adding it with account ID to azure credentials variable:

$SecPasswd = ConvertTo-SecureString "67t1uS5HfXCc9L4d3P02" -AsPlainText -Force
$AzureCred = New-Object System.Management.Automation.PSCredential ("", $SecPasswd)

Now, when credentials are set you can use Add-AzureRmAccount which adds an authenticated account to use for Azure Resource Manager cmdlet requests.

Add-AzureRmAccount -Environment AzureBros -TenantId e0527c39-0369-376d-b139-342dcd316geb -Subscription 'PowerShellBros 1' -Credential $AzureCred

Next we can use Get-AzureRMLog command with ResourceGroupName parameter to find Start/Stop information in our logs from last 30 days. I needed only 3 properties ResourceID, OperationName, EventTimeStamp:

Get-AzureRmLog -ResourceGroupName ps_bros -StartTime (Get-Date).AddDays(-30) | Select-Object ResourceID,OperationName,EventTimeStamp

As you can see above we need to adjust the output a little bit.

Get-AzureRmLog -ResourceGroupName ps_bros -StartTime (Get-Date).AddDays(-30) | Select-Object EventTimeStamp,@{name="Operation"; Expression = {$_.operationname.LocalizedValue}},@{name="ServerName"; Expression = {($_.resourceid -split "/")[-1]}}

Final script will store all results in $AllEvents variable:

$SecPasswd = ConvertTo-SecureString "67t1uS5HfXCc9L4d3P02" -AsPlainText -Force
$AzureCred = New-Object System.Management.Automation.PSCredential ("", $SecPasswd)
Add-AzureRmAccount -Environment AzureBros -TenantId e0527c39-0369-376d-b139-342dcd316geb -Subscription 'PowerShellBros 1' -Credential $azurecred
$AllEvents = Get-AzureRmLog -ResourceGroupName ps_bros -StartTime (Get-Date).AddDays(-30) | Where-Object {$_.OperationName.LocalizedValue -match "Start|Stop"} | Select-Object EventTimeStamp,@{name="Operation"; Expression = {$_.operationname.LocalizedValue}},@{name="ServerName"; Expression = {($_.resourceid -split "/")[-1]}}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.