Overview

The following article will help you configure your Aure monitoring and Alerting using a single PowerShell script

This is a continuation blog from
http://2tech.ca/enable-monitoring-and-alerting-in-azure-using-portal-part-1/

The following script will automatically create all services outlined in the following list.

1 Create a new Resource Group called Monitoring

2 Create prerequisites
2-a Create a Log Analytic Workspace called LogAnalyticWorkspace
2-b Create Storage Account

3 Configure the following settings in Log Analytical Space
3-a Enable IIS Log Collection using an agent
3-b Enable Linux Performance Counters
3-c Enable Linux Syslog Collection
3-d Enable Windows Event Collections
3-e Add Windows Performance Counters to the workspace
3-f Configure a Log Analytics workspace for VM insights
3-g Upgrade to a new solution for Azure Monitor for virtual machines
3-h Enable VM insights guest health (preview)

4 Setup Activity Log on Subscription to forward logs
4-a Setup Activity Log on Subscription to forward all events to Log Analytical Space

5 Assign Initiative to Enable Azure Monitor for VMs
5-a Assign Initiative (Enable Azure Monitor for VMs) to Resource Subscriptions
5-b Assign Managed Identity “Log Analytics Contributor” permission to subscription.

6 Microsoft Defender for Cloud ————————————————————
6-a On-board Microsoft Defender for Cloud for VM, AppServices and SQL Servers
6-b Enable auto-provisioning in the Security Center
6-c Configure Microsoft Defender for Cloud notifications

7 Create Monitor Action Group

8 Create the following Metric Monitor Alerts
8-a Create the Metric Monitor Alert for CPU High higher than 90
8-b Create the Monitor Alerts for OS Disk Queue Depth higher than 5
8-c Create the Metric Monitor Alerts for Data Disk Queue Depth higher than 5

9 Create Resource Health Alert

10 Create Administrative Log Alerts for the following actions
10-a Deleted Virtual Machine Event
10-b Deallocate Virtual Machine Event
10-c Started Virtual Machine Event
10-d Restarted Virtual Machine Event

11 Create Azure Service Health Alerts

 

Our recommendation is to run the script using the Powershell ISE tool from your workstation.

You can download scripts here
http://2tech.ca/wp-content/uploads/2021/12/Azure-Enable-Monitoring-Script.zip

You will need to install and update/install all AZ modules using the following command on your Powershell ISE

Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force

After you download the script, unzip all content to C:\Azure-Enable-Monitoring-Script folder

Those files are unpacked in the folder

Script Name

Description

Setup Azure Monitoring V11.ps1

Main script

ConfigureWorkspaceTemplate.json

3-f Configure a Log Analytics workspace for VM insights

Health.DataCollectionRule.template.json

3-h Enable VM insights guest health (preview)

resourcehealthalert.json

9-Create Resource Health Alert

ServiceHealthAlert.json

11 Create Azure Service Health Alerts

 

You will need to change these four properties to reflect your subscription and alert email address. $Subscriptionid=”xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx”
$ActionGroupEmailAddress=“user@domain.com”
$AzureSecurityCenterContactEmail=”user@domain.com”
$AzureSecurityCenterContactName=”ITSEC”

This is the content of the script.

 

# Setup Azure Monitoring on Subscription Level – V11 Created by dan@djurasovic.com on 30 Dec 2021

JSON files need to be located in “C:\Azure-Enable-Monitoring-Script” folder

This script will perform the following task on the subscription level:

Connect-AzAccount

1 Create a new Resource Group called Monitoring

2 Create prerequisites

# 2-a Create Log Analytic Workspace called LogAnalyticWorkspace
# 2-b Create Storage Account

3 Configure the following settings in Log Analytical Space

# 3-a Enable IIS Log Collection using an agent
# 3-b Enable Linux Performance Counters
# 3-c Enable Linux Syslog Collection
# 3-d Enable Windows Event Collections
# 3-e Add Windows Performance Counters to the workspace
# 3-f Configure a Log Analytics workspace for VM insights
# 3-g Upgrade to a new solution for Azure Monitor for virtual machines
# 3-h Enable VM insights guest health (preview)

4 Setup Activity Log on Subscription to forward logs

# 4-a Setup Activity Log on Subscription to forwarding all events to Log Analytical Space

5 Assign Initiative to Enable Azure Monitor for VMs

# 5-a Assign Initiative (Enable Azure Monitor for VMs) to Resource Subscriptions
# 5-b Assign Managed Identity “Log Analytics Contributor” permission to subscription.

6 Azure Security Center

# 6-a On-board Azure Security Center for VM, AppServices and SQL Servers
# 6-b Enable auto-provisioning in the Security Center
# 6-c Configure Azure Security Center notifications

7 Create Monitor Action Group

8 Create the following Metric Monitor Alerts

# 8-a Create the Metric Monitor Alert for CPU High higher than 90
# 8-b Create the Monitor Alerts for OS Disk Queue Depth higher than 5
# 8-c Create the Metric Monitor Alerts for Data Disk Queue Depth higher than 5

9 Create Resource Health Alert

10 Create Administrative Log Alerts for the following actions

# 10-a Deleted Virtual Machine Event
# 10-b Deallocate Virtual Machine Event
# 10-c Started Virtual Machine Event
# 10-d Restarted Virtual Machine Event

11 Create Azure Service Health Alerts

# The following three files are used during configuration—————————————————————-
# – ConfigureWorkspaceTemplate.json
# – Health.DataCollectionRule.template.json
# – resourcehealthalert.json

———————————————————–

Mandatory Variable

Enter email address for action alert group

Get-AzSubscription | select name,id
$Subscriptionid=”5615d081-a433-484f-a4e2-c8e650ca8bdf”
$ActionGroupEmailAddress=”user@domain.com”
$AzureSecurityCenterContactEmail=”user@domain.com”
$AzureSecurityCenterContactName=”ITSEC”

Other Optional Variables

$Location=”CanadaCentral”
$ResourceGroup=”Monitoring”
$WorkspaceName=”LogAnalyticWorkspace”
$DiagnosticSettingName = ‘Send Logs to LogAnalytical Workspace’
$ActionGroupName=”ActionGroup”
$FilePath=”C:\Azure-Enable-Monitoring-Script”

$AzureSecurityCenterContactName=”ITSEC”
$AzureSecurityCenterContactEmail=”user@domain.com”

0 SetUp Subscription Context

Write-host -ForegroundColor Green 0 SetUp Subscription Context
Set-AzContext -Subscription $SubscriptionId
$SubscriptionName=Get-AzSubscription -SubscriptionId $Subscriptionid | Select-Object -ExpandProperty Name

1 Create a new Resource Group

Write-host -ForegroundColor Green 1 Create a new Resource Group
New-AzResourceGroup -Name $ResourceGroup -Location $Location

2-a Create Log Analytic Workspace called LogAnalyticWorkspace

Write-host -ForegroundColor Green 2a Create Log Analytic Workspace called LogAnalyticWorkspace
New-AzOperationalInsightsWorkspace -Location $Location -Name $WorkspaceName -Sku Standard -ResourceGroupName $ResourceGroup

Get Log Analytic WorkSpace ID

$Workspace=Get-AzOperationalInsightsWorkspace -Name $WorkspaceName -ResourceGroupName $ResourceGroup
$WorkspaceId=$workspace.ResourceId

2-b Create Storage Account

Write-host -ForegroundColor Green 2-b Checking if Storage Account is already created

$RandomNumber= Get-Random
$StorageAccountNameInitial = “monitorstorage” + $RandomNumber
$STORAGE_ACCOUNT = Get-AzStorageAccount -ResourceGroupName $ResourceGroup | Where-Object {$_.StorageAccountName -like “monitorstorage*”} -ErrorAction Ignore

if ($STORAGE_ACCOUNT -eq $null) {
Write-Host -ForegroundColor Green ‘2-b Creating storage account’ $StorageAccountNameInitial
New-AzStorageAccount -ResourceGroupName $ResourceGroup -AccountName $StorageAccountNameInitial -Location $Location -SkuName Standard_LRS -Kind StorageV2 -AccessTier Hot
Write-Host -ForegroundColor Green “$StorageAccountNameInitial storage account successfully created.”
}
else {
Write-Host -ForegroundColor Green ‘Storage account already exists, script is continuing.’
}

$StorageAccount=Get-AzStorageAccount -ResourceGroupName $ResourceGroup | Where-Object {$_.StorageAccountName -like “monitorstorage*”}
$StorageAccountID=$StorageAccount.id
$StorageAccountName=$StorageAccount.StorageAccountName

3 Configure the following settings in Log AnalyticalSpace

3-a Enable IIS Log Collection using an agent

Write-host -ForegroundColor Green 3-a Enable IIS Log Collection using an agent
Enable-AzOperationalInsightsIISLogCollection -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName

3-b Enable Linux Performance Counters

Write-host -ForegroundColor Green 3-b Enable Linux Performance Counters
New-AzOperationalInsightsLinuxPerformanceObjectDataSource -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -ObjectName “Logical Disk” -InstanceName “” -CounterNames @(“% Used Inodes”, “Free Megabytes”, “Disk Transfers/sec”, “Disk Reads/sec”, “Disk Writes/sec”, “% Free Space” ) -IntervalSeconds 60 -Name “Linux Disk Performance Counters” -Force New-AzOperationalInsightsLinuxPerformanceObjectDataSource -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -ObjectName “Processor” -InstanceName “” -CounterNames “% Processor Time” -IntervalSeconds 60 -Name “Processor Time” -Force
New-AzOperationalInsightsLinuxPerformanceObjectDataSource -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -ObjectName “Memory” -InstanceName “” -CounterNames “% Available Memory” -IntervalSeconds 60 -Name “Percent Available Memory” -Force New-AzOperationalInsightsLinuxPerformanceObjectDataSource -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -ObjectName “System” -InstanceName “” -CounterNames “Uptime” -IntervalSeconds 3600 -Name “uptime” -Force
Enable-AzOperationalInsightsLinuxPerformanceCollection -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName

3-c Enable Linux Syslog Collection

Write-host -ForegroundColor Green 3-c Enable Linux Syslog Collection
New-AzOperationalInsightsLinuxSyslogDataSource -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -Facility “kern” -CollectEmergency -CollectAlert -CollectCritical -CollectError -CollectWarning -Name “kernel syslog collection” -force
New-AzOperationalInsightsLinuxSyslogDataSource -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -Facility “auth” -CollectEmergency -CollectAlert -CollectCritical -CollectError -CollectWarning -Name “auth syslog collection” -Force
New-AzOperationalInsightsLinuxSyslogDataSource -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -Facility “daemon” -CollectEmergency -CollectAlert -CollectCritical -CollectError -CollectWarning -Name “daemon syslog collection” -Force
New-AzOperationalInsightsLinuxSyslogDataSource -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -Facility “syslog” -CollectEmergency -CollectAlert -CollectCritical -CollectError -CollectWarning -Name “syslog syslog collection” -Force
Enable-AzOperationalInsightsLinuxSyslogCollection -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName

3-d Enable Windows Event Collections

Write-host -ForegroundColor Green 3-d Enable Windows Event Collections
New-AzOperationalInsightsWindowsEventDataSource -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -EventLogName “Application” -CollectErrors -CollectWarnings -Name “Application Event Log” -force
New-AzOperationalInsightsWindowsEventDataSource -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -EventLogName “System” -CollectErrors -CollectWarnings -Name “System Event Log” -force

3-e Add Windows Performance Counters to the workspace

Write-host -ForegroundColor Green 3-e Add Windows Performance Counters to the workspace

$perfCounters = ‘LogicalDisk()\% Free Space’, ‘LogicalDisk()\Disk Reads/sec’,
‘LogicalDisk()\Disk Transfers/sec’, ‘LogicalDisk()\Disk Writes/sec’,
‘LogicalDisk()\Free Megabytes’, ‘Processor(_Total)\% Processor Time’, ‘Network Adapter()\Bytes Received/sec’,
‘Network Adapter(*)\Bytes Sent/sec’

foreach ($perfCounter in $perfCounters) {
$perfArray = $perfCounter.split(“\”).split(“(“).split(“)”)
$objectName = $perfArray[0]
$instanceName = $perfArray[1]
$counterName = $perfArray[3]
$name = (“$objectName-$counterName”) -replace “/”, “Per” -replace “%”, “Percent”
write-output $name
New-AzOperationalInsightsWindowsPerformanceCounterDataSource -ErrorAction Continue -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -ObjectName $objectName -InstanceName $instanceName -CounterName $counterName
-IntervalSeconds 60 -Name $name -Force

}

3-f Configure a Log Analytics workspace for VM insights

Write-host -ForegroundColor Green 3-f Configure a Log Analytics workspace for VM insights
New-AzResourceGroupDeployment -Name ConfigureWorkspace -ResourceGroupName $ResourceGroup -TemplateFile “$FilePath\ConfigureWorkspaceTemplate.json” -workspaceResourceId $WorkspaceId -WorkspaceLocation $location

3-g Upgrade to a new solution for Azure Monitor for virtual machines

Write-host -ForegroundColor Green 3-g Upgrade to a new solution for Azure Monitor for virtual machines
Set-AzOperationalInsightsIntelligencePack -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -IntelligencePackName “VMInsights” -Enabled $True

3-h Enable VM insights guest health

Write-host -ForegroundColor Green 3-h Enable VM insights guest health
New-AzResourceGroupDeployment -Name GuestHealthDataCollectionRule -ResourceGroupName $ResourceGroup -TemplateFile “$FilePath\Health.DataCollectionRule.template.json” -destinationWorkspaceResourceId $WorkspaceId -dataCollectionRuleLocation $Location

4 Setup Activity Log on Subscription to forward logs

4-a Setup Activity Log on Subscription to forwarding all events to Log Analytical Space

Write-host -ForegroundColor Green 4-a Setup Activity Log on Subscription to forwarding all events to Log Analytical Space
$list = @()
Get-AzSubscriptionDiagnosticSettingCategory | ForEach-Object {
$list += (New-AzDiagnosticDetailSetting -Log -Category $_.Name -Enabled)
}
$setting = New-AzDiagnosticSetting -Name $DiagnosticSettingName -SubscriptionId $SubscriptionId -WorkspaceId $Workspace.resourceid -Setting $list
Set-AzDiagnosticSetting -InputObject $setting

5 Assign Initiative to Enable Azure Monitor for VMs

5-a Assign Initiative (Enable Azure Monitor for VMs) to Resource Subscriptions

Write-host -ForegroundColor Green 5-a Assign Initiative Enable Azure Monitor for VMs to Resource Subscriptions
$PolicyAssignmentName=”Enable Azure Monitor for VMs”
$Policy = Get-AzPolicysetDefinition -Builtin | Where-Object {$_.Properties.DisplayName -eq “Enable Azure Monitor for VMs”}
$Parameter = @{‘logAnalytics_1’=($Workspace.ResourceId)}
New-AzPolicyAssignment -Name $PolicyAssignmentName -PolicySetDefinition $Policy -Scope “/subscriptions/$SubscriptionId” -PolicyParameterObject $Parameter -Location $location -AssignIdentity

5-b Assign Managed Identity “Log Analytics Contributor” permission to subscription.

Write-host -ForegroundColor Green 5-b Assign Managed Identity Log Analytics Contributon permission to subscription.

Suspend Script for 90 sec

Write-host -ForegroundColor Green Suspend Script for 30 sec

for($i = 0; $i -le 100; $i++)
{
Write-Progress -Activity “Activity” -PercentComplete $i -Status “Waiting 30 sec for Configuration to propagate to Azure BackEnd”;
Sleep -Milliseconds 300;
}

$PolicyAssignment=Get-AzPolicyAssignment -Name $PolicyAssignmentName -Scope “/subscriptions/$SubscriptionId”
$objectID = GUID
New-AzRoleAssignment -Scope “/subscriptions/$SubscriptionId” -ObjectId $objectID -RoleDefinitionName “Log Analytics Contributor”

6 Microsoft Defender for Cloud

6-a On-board Microsoft Defender for Cloud for VM, AppServices and SQL Servers

Write-host -ForegroundColor Green 6-a On-board Azure Security Center for VM, AppServices and SQL Servers
Register-AzResourceProvider -ProviderNamespace ‘Microsoft.Security’
Set-AzSecurityPricing -Name “VirtualMachines” -PricingTier “Standard”
Set-AzSecurityPricing -Name “AppServices” -PricingTier “Standard”
Set-AzSecurityPricing -Name “SqlServers” -PricingTier “Standard”

6-b Enable auto-provisioning in the Security Center

Write-host -ForegroundColor Green 6-b Enable auto-provisioning in the Security Center
Set-AzSecurityAutoProvisioningSetting -Name “default” -EnableAutoProvision

6-c Configure Microsoft Defender for Cloud notifications

Write-host -ForegroundColor Green 6-c Configure Azure Security Center notifications

Set-AzSecurityContact -Name $AzureSecurityCenterContactName -Email $AzureSecurityCenterContactEmail -AlertAdmin -NotifyOnAlert

7 Create Monitor Action Group

Write-host -ForegroundColor Green 7 Create Monitor Action Group
$EmailReceiver = New-AzActionGroupReceiver -Name $ActionGroupName -EmailReceiver -EmailAddress $ActionGroupEmailAddress
Set-AzActionGroup -Name $ActionGroupName -ResourceGroupName “$ResourceGroup” -ShortName $ActionGroupName -Receiver $EmailReceiver
$ActionGroupID=Get-AzActionGroup -name $ActionGroupName -ResourceGroupName “$ResourceGroup” | select Id
$ActionGroup=Get-AzActionGroup -name $ActionGroupName -ResourceGroupName “$ResourceGroup”

8 Create the following Metric Monitor Alerts

8-a Create the Metric Monitor Alert for CPU High higher than 90

Write-host -ForegroundColor Green 8-a Create the Metric Monitor Alert for CPU High higher than 90
$actionGroup = Get-AzActionGroup -Name $ActionGroupName -ResourceGroupName $ResourceGroup
$actionGroupId = New-AzActionGroup -ActionGroupId $actionGroup.Id
$windowSize = New-TimeSpan -Minutes 1
$frequency = New-TimeSpan -Minutes 1
$condition = New-AzMetricAlertRuleV2Criteria -MetricName “Percentage CPU” -TimeAggregation Average -Operator GreaterThan -Threshold 90
$context = Get-AzContext
$Description = “This is alerts which is triggered when CPU on VM has high utilization.”
Add-AzMetricAlertRuleV2 -Name “CPU Utilization Alert” -ResourceGroupName $ResourceGroup -WindowSize $windowSize -Frequency $frequency -TargetResourceScope “/subscriptions/$Subscriptionid” -TargetResourceType “Microsoft.Compute/virtualMachines” -TargetResourceRegion $Location -Description $Description -Condition $condition -Severity 3 -ActionGroup $actionGroupId

8-b Create the Monitor Alerts for OS Disk Queue Depth higher than 5

Write-host -ForegroundColor Green 8-b Create the Monitor Alerts for OS Disk Queue Depth higher than 5
$actionGroup = Get-AzActionGroup -Name $ActionGroupName -ResourceGroupName $ResourceGroup
$actionGroupId = New-AzActionGroup -ActionGroupId $actionGroup.Id
$windowSize = New-TimeSpan -Minutes 1
$frequency = New-TimeSpan -Minutes 1
$condition = New-AzMetricAlertRuleV2Criteria -MetricName “OS Disk Queue Depth” -TimeAggregation Maximum -Operator GreaterThan -Threshold 5
$context = Get-AzContext
$Description = “This is alerts which is triggered when OS Disk Queue Depth on VM has high utilization.”
Add-AzMetricAlertRuleV2 -Name “OS Disk Queue Depth Alert” -ResourceGroupName $ResourceGroup -WindowSize $windowSize -Frequency $frequency -TargetResourceScope “/subscriptions/$Subscriptionid” -TargetResourceType “Microsoft.Compute/virtualMachines” -TargetResourceRegion $Location -Description $Description -Condition $condition -Severity 3 -ActionGroup $actionGroupId

8-c Create the Metric Monitor Alerts for Data Disk Queue Depth higher than 5

Write-host -ForegroundColor Green 8-c Create the Metric Monitor Alerts for Data Disk Queue Depth higher than 5
$actionGroup = Get-AzActionGroup -Name $ActionGroupName -ResourceGroupName $ResourceGroup
$actionGroupId = New-AzActionGroup -ActionGroupId $actionGroup.Id
$windowSize = New-TimeSpan -Minutes 1
$frequency = New-TimeSpan -Minutes 1
$condition = New-AzMetricAlertRuleV2Criteria -MetricName “Data Disk Queue Depth” -TimeAggregation Maximum -Operator GreaterThan -Threshold 5
$context = Get-AzContext
$Description = “This is alerts which is triggered when Data Disk Queue Depth on VM has high utilization.”
Add-AzMetricAlertRuleV2 -Name “Data Disk Queue Depth Alert” -ResourceGroupName $ResourceGroup -WindowSize $windowSize -Frequency $frequency -TargetResourceScope “/subscriptions/$Subscriptionid” -TargetResourceType “Microsoft.Compute/virtualMachines” -TargetResourceRegion $Location -Description $Description -Condition $condition -Severity 3 -ActionGroup $actionGroupId

 

9 Create Resource Health Alert

Write-host -ForegroundColor Green 9 Create Resource Health Alert
$Name=”Resource Health Alert”
New-AzResourceGroupDeployment -Name ResourceHealthAlertDeployment -ResourceGroupName $ResourceGroup -activityLogAlertName $Name -actionGroupResourceId $ActionGroup.id -TemplateFile “$FilePath\resourcehealthalert.json”

10 Create Administrative Log Alerts for the following actions

Write-host -ForegroundColor Green 10-a Deleted Virtual Machine Event
$condition1 = New-AzActivityLogAlertCondition -Field ‘category’ -Equal ‘Administrative’
$condition2 = New-AzActivityLogAlertCondition -Field ‘operationName’ -Equal ‘Microsoft.Network/networkSecurityGroups/delete’
Set-AzActivityLogAlert -Location “Global” -Name “Deleted Virtual Machine Event” -ResourceGroupName $resourcegroup -Scope “/subscriptions/$SubscriptionId” -Action $ActionGroupID -Condition $condition1,$condition2

10-b Deallocate Virtual Machine Event

Write-host -ForegroundColor Green 10-b Deallocate Virtual Machine Event
$condition1 = New-AzActivityLogAlertCondition -Field ‘category’ -Equal ‘Administrative’
$condition2 = New-AzActivityLogAlertCondition -Field ‘operationName’ -Equal ‘Microsoft.Compute/virtualMachines/deallocate/action’
Set-AzActivityLogAlert -Location “Global” -Name “Deallocate Virtual Machine Event” -ResourceGroupName $resourcegroup -Scope “/subscriptions/$SubscriptionId” -Action $ActionGroupID -Condition $condition1,$condition2

10-c Started Virtual Machine Event

Write-host -ForegroundColor Green 10-c Started Virtual Machine Event
$condition1 = New-AzActivityLogAlertCondition -Field ‘category’ -Equal ‘Administrative’
$condition2 = New-AzActivityLogAlertCondition -Field ‘operationName’ -Equal ‘Microsoft.Compute/virtualMachines/start/action’
Set-AzActivityLogAlert -Location “Global” -Name “Started Virtual Machine Event” -ResourceGroupName $resourcegroup -Scope “/subscriptions/$SubscriptionId” -Action $ActionGroupID -Condition $condition1,$condition2

10-d Restarted Virtual Machine Event

Write-host -ForegroundColor Green 10-d Restarted Virtual Machine Event
$condition1 = New-AzActivityLogAlertCondition -Field ‘category’ -Equal ‘Administrative’
$condition2 = New-AzActivityLogAlertCondition -Field ‘operationName’ -Equal ‘Microsoft.Compute/virtualMachines/restart/action’
Set-AzActivityLogAlert -Location “Global” -Name “Restared Virtual Machine Event” -ResourceGroupName $resourcegroup -Scope “/subscriptions/$SubscriptionId” -Action $ActionGroupID -Condition $condition1,$condition2

11 Create Azure Service Health Alerts

Write-host -ForegroundColor Green 11 Create Azure Service Health Alerts

$ServiceHealthRegions = @(
“Canada Central”,
“Canada East”
“Global”
)

$ServiceHealthServices = @(
“Action Groups”,
“Activity Logs & Alerts”,
“Alerts & Metrics”,
“Alerts”,
“Application Insights”,
“Azure Active Directory”,
“Virtual Machines”,
“Virtual Network”,
“Storage”,
“Microsoft Azure Portal”,
“App Service”,
“Backup”,
“Azure Active Directory Domain Services”
)

$ServiceHealthServices = @(
“Select all”
)

$actiongroup = Get-AzActionGroup -Name $ActionGroupName -ResourceGroup “$ResourceGroup” -WarningAction Ignore

$params = @{
LogAlertName = “Service Health Alerts 2”
ServiceHealthRegions = $ServiceHealthRegions
ServiceHealthServices = $ServiceHealthServices
actiongroupresourceid = $actiongroup.id

}

New-AzResourceGroupDeployment -Name “ServiceHealthAlerts” -ResourceGroupName “$ResourceGroup” -TemplateFile “C:\Azure-Enable-Monitoring-Script\ServiceHealthAlert.json” -TemplateParameterObject $params

The end of the script

Write-host -ForegroundColor green All Configuration has been applied.

By Dan Djurasovic

Dan is an Azure Technical Advisor, with over a dozen years of IT experience, specializing in Microsoft Office 365, Exchange Server Azure IaaS and Active Directory..

2 thought on “Configure Azure Monitoring and alerting using PowerShell Script.”
  1. Excellent Script Dan. Have you updated this at all or is v11 the latest one? Also I don’t suppose you have this same script but in terraform do you?

    Thanks again

  2. Hi Dan,

    great work 🙂
    is there a new version or is v11 the latest one?

    greetings
    Markus

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.