Azure / azure-powershell

Microsoft Azure PowerShell
Other
4.21k stars 3.82k forks source link

Add-AzMetricAlertRuleV2 alerts do not show up in resource graph or Get-AzScheduledQueryRule #16262

Closed rachaelsingleton closed 2 years ago

rachaelsingleton commented 2 years ago

Description

When creating a metric alert through PowerShell, the created alerts to not show up in resource graph or Get-AzScheduledQueryRule like they do when creating through the portal. The properties and configs appear to be the same.

If I modify one property (a condition operator for example), of an alert created via PS and save it in the portal, the alert will show up.

Steps to reproduce

$workspace = get-azoperationalinsightsworkspace -ResourceGroupName $resourceGroup.ResourceGroupName

$ActionGroup = Get-AzActionGroup 

$dim = New-AzMetricAlertRuleV2DimensionSelection -DimensionName "Computer" -ValuesToInclude "*"

$criteria = New-AzMetricAlertRuleV2Criteria -MetricName "Heartbeat" `
-DimensionSelection $dim `
-TimeAggregation Total `
-Operator LessThan `
-threshold 1

Add-AzMetricAlertRuleV2 -Name "Server Down" `
-Description "Server Down" `
-ResourceGroupName $workspace.resourcegroupname `
-WindowSize 0:5 `
-Frequency 0:1 `
-TargetResourceType "Microsoft.OperationalInsights/workspaces" `
-TargetResourceScope $workspace.ResourceId `
-TargetResourceRegion $resourceGroup.Location `
-Condition $criteria `
-ActionGroupId $ActionGroup.Id`
-Severity 0 `
-AutoMitigate $false

Environment data

Name                           Value                                           
----                           -----                                           
PSVersion                      5.1.19041.1023                                  
PSEdition                      Desktop                                         
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                         
BuildVersion                   10.0.19041.1023                                 
CLRVersion                     4.0.30319.42000                                 
WSManStackVersion              3.0                                             
PSRemotingProtocolVersion      2.3                                             
SerializationVersion           1.1.0.1      

Module versions

Script     2.5.2      Az.Accounts                         {Add-AzEnvironment...
Script     4.14.0     Az.Compute                          {Add-AzImageDataDi...
Script     2.7.0      Az.Monitor                          {Add-AzAutoscaleSe...
Script     2.3.0      Az.OperationalInsights              {Disable-AzOperati...
Script     4.2.0      Az.Resources                        {Add-AzADGroupMemb...
dingmeng-xue commented 2 years ago

Thanks for reporting. We will look into it. Could you provide the debug message around Add-AzMetricAlertRuleV2 execution. You can turn on it via $DebugPreference= "Continue"

ghost commented 2 years ago

Hi, we're sending this friendly reminder because we haven't heard back from you in a while. We need more information about this issue to help address it. Please be sure to give us your input within the next 7 days. If we don't hear back from you within 14 days of this comment the issue will be automatically closed. Thank you!

rachaelsingleton commented 2 years ago

I will get this to you today

Thanks for reporting. We will look into it. Could you provide the debug message around Add-AzMetricAlertRuleV2 execution. You can turn on it via $DebugPreference= "Continue"

rachaelsingleton commented 2 years ago
EBUG: 3:55:52 PM - GetAzureOperationalInsightsWorkspaceCommand begin processing with Pa
rameterSet '__AllParameterSets'.
DEBUG: 3:55:52 PM - using account id ''...
DEBUG: [Common.Authentication]: Authenticating using Account: '', 
environment: 'AzureCloud', tenant: ''
DEBUG: 3:55:52 PM - [SilentAuthenticator] Calling SharedTokenCacheCredential.GetTokenAsy
nc - TenantId:'', Scopes:'https://management.core.wi
ndows.net//.default', AuthorityHost:'https://login.microsoftonline.com/', UserId:''
DEBUG: SharedTokenCacheCredential.GetToken invoked. Scopes: [ https://management.core.wi
ndows.net//.default ] ParentRequestId: 
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52 - ]
 Azure region was not configured or could not be discovered. Not using a regional author
ity.
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52] Fo
und 1 cache accounts and 0 broker accounts
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52] Re
turning 1 accounts
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52 - ]
 MSAL MSAL.Desktop with assembly version '4.30.1.0'. CorrelationId(fede7577-7518-46f0-87
86-fed4c388b2d4)
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52 - ]
 === AcquireTokenSilent Parameters ===
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52 - ]
 LoginHint provided: False
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52 - ]
 Account provided: True
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52 - ]
 ForceRefresh: False
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52 - ]

=== Request Data ===
Authority Provided? - True
Scopes - https://management.core.windows.net//.default
Extra Query Params Keys (space separated) - 
ApiId - AcquireTokenSilent
IsConfidentialClient - False
SendX5C - False
LoginHint ? False
IsBrokerConfigured - False
HomeAccountId - False
CorrelationId - fede7577-7518-46f0-8786-fed4c388b2d4

DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52 - ]
 === Token Acquisition (SilentRequest) started:

    Authority Host: login.microsoftonline.com
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52 - ]
 Azure region was not configured or could not be discovered. Not using a regional author
ity.
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52 - ]
 Access token is not expired. Returning the found cache entry. [Current time (11/15/2021
 20:55:52) - Expiration Time (11/15/2021 21:56:05 +00:00) - Extended Expiration Time (11
/15/2021 21:56:05 +00:00)]
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52 - ]
 Returning access token found in cache. RefreshOn exists ? False
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52 - ]
 Fetched access token from host login.microsoftonline.com. 
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:52 - ]
 === Token Acquisition finished successfully. An access token was returned with Expirati
on Time: 11/15/2021 21:56:05 +00:00 and Scopes https://management.core.windows.net//user
_impersonation https://management.core.windows.net//.default
DEBUG: SharedTokenCacheCredential.GetToken succeeded. Scopes: [ https://management.core.
windows.net//.default ] ParentRequestId:  ExpiresOn: 2021-11-15T21:56:05.0000000+00:00
DEBUG: [Common.Authentication]: Received token with LoginType 'User', Tenant: 'fde7faeb-
fdf2-4737-aec7-50ff8ce93c50', UserId: ''
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

Absolute Uri:
https://management.azure.com/subscriptions/<>/resource
groups/<>/providers/Microsoft.OperationalInsights/workspaces/LogWorkspace?ap
i-version=2020-03-01-preview

Headers:
x-ms-client-request-id        : 98090689-cf6a-45bf-a68f-8e15a1878d6b
accept-language               : en-US

Body:

DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-request-id               : 81d09f4b-b15c-4922-9f83-6addc3f8e080
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
Cache-Control                 : no-cache
Server                        : Microsoft-IIS/10.0,Microsoft-IIS/10.0
X-Powered-By                  : ASP.NET,ASP.NET
x-ms-ratelimit-remaining-subscription-reads: 11999
x-ms-correlation-request-id   : 1865c3fd-50cb-42c7-b433-490ddeb6bad2
x-ms-routing-request-id       : EASTUS2:20211115T205552Z:1865c3fd-50cb-42c7-b433-490ddeb
6bad2
Date                          : Mon, 15 Nov 2021 20:55:51 GMT

Body:
{
  "properties": {
    "source": "Azure",
    "customerId": "<>",
    "provisioningState": "Succeeded",
    "sku": {
      "name": "pergb2018",
      "lastSkuUpdate": "Wed, 13 Oct 2021 13:53:42 GMT"
    },
    "retentionInDays": 30,
    "features": {
      "legacy": 0,
      "searchVersion": 1,
      "enableLogAccessUsingOnlyResourcePermissions": true
    },
    "workspaceCapping": {
      "dailyQuotaGb": -1.0,
      "quotaNextResetTime": "Tue, 16 Nov 2021 13:00:00 GMT",
      "dataIngestionStatus": "RespectQuota"
    },
    "publicNetworkAccessForIngestion": "Enabled",
    "publicNetworkAccessForQuery": "Enabled",
    "createdDate": "Wed, 13 Oct 2021 13:53:42 GMT",
    "modifiedDate": "Wed, 13 Oct 2021 13:55:08 GMT"
  },
  "id": "/subscriptions/<>/resourcegroups/<>/p
roviders/microsoft.operationalinsights/workspaces/logworkspace",
  "name": "LogWorkspace",
  "type": "Microsoft.OperationalInsights/workspaces",
  "location": "eastus"
}

Survey: How was your experience using Azure PowerShell?
Run Open-AzSurveyLink to fill out a short Survey
DEBUG: AzureQoSEvent: Module: Az.OperationalInsights:2.3.0; CommandName: Get-AzOperation
alInsightsWorkspace; PSVersion: 5.1.19041.1023; IsSuccess: True; Duration: 00:00:00.6079
165
DEBUG: Finish sending metric.
DEBUG: 3:55:53 PM - GetAzureOperationalInsightsWorkspaceCommand end processing.
DEBUG: 3:55:53 PM - NewAzureRmMetricAlertRuleV2DimensionSelectionCommand begin processin
g with ParameterSet '__AllParameterSets'.
DEBUG: 3:55:53 PM - using account id ''...
WARNING: 3:55:53 PM - The namespace for all the model classes will change from Microsoft
.Azure.Management.Monitor.Management.Models to Microsoft.Azure.Management.Monitor.Models
 in future releases.
WARNING: 3:55:53 PM - The namespace for output classes will be uniform for all classes i
n future releases to make it independent of modifications in the model classes.
DEBUG: AzureQoSEvent: Module: Az.Monitor:2.7.0; CommandName: New-AzMetricAlertRuleV2Dime
nsionSelection; PSVersion: 5.1.19041.1023; IsSuccess: True; Duration: 00:00:00.0212631
DEBUG: Finish sending metric.
DEBUG: 3:55:54 PM - NewAzureRmMetricAlertRuleV2DimensionSelectionCommand end processing.
DEBUG: 3:55:54 PM - NewAzureRmMetricAlertRuleV2CriteriaCommand begin processing with Par
ameterSet 'StaticThresholdParameterSet'.
DEBUG: 3:55:54 PM - using account id ''...
WARNING: 3:55:54 PM - The namespace for all the model classes will change from Microsoft
.Azure.Management.Monitor.Management.Models to Microsoft.Azure.Management.Monitor.Models
 in future releases.
WARNING: 3:55:54 PM - The namespace for output classes will be uniform for all classes i
n future releases to make it independent of modifications in the model classes.
DEBUG: AzureQoSEvent: Module: Az.Monitor:2.7.0; CommandName: New-AzMetricAlertRuleV2Crit
eria; PSVersion: 5.1.19041.1023; IsSuccess: True; Duration: 00:00:00.0228096
DEBUG: Finish sending metric.
DEBUG: 3:55:54 PM - NewAzureRmMetricAlertRuleV2CriteriaCommand end processing.
DEBUG: 3:55:54 PM - AddAzureRmMetricAlertRuleV2Command begin processing with ParameterSe
t 'CreateAlertByResourceId'.
DEBUG: 3:55:54 PM - using account id ''...
WARNING: 3:55:54 PM - The namespace for all the model classes will change from Microsoft
.Azure.Management.Monitor.Management.Models to Microsoft.Azure.Management.Monitor.Models
 in future releases.
WARNING: 3:55:54 PM - The namespace for output classes will be uniform for all classes i
n future releases to make it independent of modifications in the model classes.
DEBUG: [Common.Authentication]: Authenticating using Account: '', environment: 'AzureCloud', tenant: '<>'
DEBUG: 3:55:54 PM - [SilentAuthenticator] Calling SharedTokenCacheCredential.GetTokenAsync - TenantId:'', Scop
es:'https://management.core.windows.net//.default', AuthorityHost:'https://login.microsoftonline.com/', UserId:''
DEBUG: SharedTokenCacheCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: 
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54 - ] Azure region was not configured or could not be discovere
d. Not using a regional authority.
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54] Found 1 cache accounts and 0 broker accounts
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54] Returning 1 accounts
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54 - ] MSAL MSAL.Desktop with assembly version '4.30.1.0'. Corre
lationId(66a1e945-3818-45bf-9381-3e8ec02226c3)
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54 - ] === AcquireTokenSilent Parameters ===
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54 - ] LoginHint provided: False
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54 - ] Account provided: True
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54 - ] ForceRefresh: False
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54 - ] 
=== Request Data ===
Authority Provided? - True
Scopes - https://management.core.windows.net//.default
Extra Query Params Keys (space separated) - 
ApiId - AcquireTokenSilent
IsConfidentialClient - False
SendX5C - False
LoginHint ? False
IsBrokerConfigured - False
HomeAccountId - False
CorrelationId - 66a1e945-3818-45bf-9381-3e8ec02226c3

DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54 - ] === Token Acquisition (SilentRequest) started:

    Authority Host: login.microsoftonline.com
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54 - ] Azure region was not configured or could not be discovere
d. Not using a regional authority.
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54 - ] Access token is not expired. Returning the found cache en
try. [Current time (11/15/2021 20:55:54) - Expiration Time (11/15/2021 21:56:05 +00:00) - Extended Expiration Time (11/15/2021 21:56:05 +00:00)]
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54 - ] Returning access token found in cache. RefreshOn exists ?
 False
DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54 - ] Fetched access token from host login.microsoftonline.com.

DEBUG: (False) MSAL 4.30.1.0 MSAL.Desktop Windows 10 Enterprise [11/15/2021 20:55:54 - ] === Token Acquisition finished successfully. An access to
ken was returned with Expiration Time: 11/15/2021 21:56:05 +00:00 and Scopes https://management.core.windows.net//user_impersonation https://manag
ement.core.windows.net//.default
DEBUG: SharedTokenCacheCredential.GetToken succeeded. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId:  ExpiresOn: 2021-
11-15T21:56:05.0000000+00:00
DEBUG: [Common.Authentication]: Received token with LoginType 'User', Tenant: '', UserId: '<>.
COM'
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
PUT

Absolute Uri:
https://management.azure.com/subscriptions/<>/resourceGroups/<>/providers/Microsoft.Insights/metricAlert
s/ - Server Down?api-version=2018-03-01

Headers:
x-ms-client-request-id        : c4900131-80fb-4626-8a67-4129451de987
accept-language               : en-US

Body:
{
  "properties": {
    "description": "Server Down",
    "severity": 0,
    "enabled": true,
    "scopes": [
      "/subscriptions/<>/resourcegroups/<>/providers/microsoft.operationalinsights/workspaces/logwor
kspace"
    ],
    "evaluationFrequency": "PT1M",
    "windowSize": "PT5M",
    "criteria": {
      "odata.type": "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria",
      "allOf": [
        {
          "criterionType": "StaticThresholdCriterion",
          "operator": "LessThan",
          "threshold": 1.0,
          "name": "metric1",
          "metricName": "Heartbeat",
          "timeAggregation": "Total",
          "dimensions": [
            {
              "name": "Computer",
              "operator": "Include",
              "values": [
                "*"
              ]
            }
          ],
          "skipMetricValidation": false
        }
      ]
    },
    "autoMitigate": false,
    "actions": []
  },
  "location": "global"
}

DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
OK

Headers:
Pragma                        : no-cache
Vary                          : Accept-Encoding
x-ms-request-id               : a3206c2a-1103-4ca9-a05f-e1564ca7fac3,a3206c2a-1103-4ca9-a05f-e1564ca7fac3,a3206c2a-1103-4ca9-a05f-e1564ca7fac3
api-supported-versions        : 2017-09-01-preview, 2018-03-01
Strict-Transport-Security     : max-age=31536000; includeSubDomains
Arr-Disable-Session-Affinity  : true
X-Content-Type-Options        : nosniff
x-ms-ratelimit-remaining-subscription-resource-requests: 299
x-ms-correlation-request-id   : a3206c2a-1103-4ca9-a05f-e1564ca7fac3
x-ms-routing-request-id       : EASTUS2:20211115T205559Z:a3206c2a-1103-4ca9-a05f-e1564ca7fac3
Cache-Control                 : no-cache
Date                          : Mon, 15 Nov 2021 20:55:58 GMT
Server                        : Microsoft-IIS/10.0
X-AspNet-Version              : 4.0.30319
X-Powered-By                  : ASP.NET

Body:
{
  "id": "/subscriptions/<>/resourceGroups/<>/providers/Microsoft.Insights/metricAlerts/ - Server Dow
n",
  "name": " - Server Down",
  "type": "Microsoft.Insights/metricAlerts",
  "location": "global",
  "properties": {
    "description": "Server Down",
    "severity": 0,
    "enabled": true,
    "scopes": [
      "/subscriptions/<>/resourcegroups/<>/providers/microsoft.operationalinsights/workspaces/logwor
kspace"
    ],
    "evaluationFrequency": "PT1M",
    "windowSize": "PT5M",
    "criteria": {
      "allOf": [
        {
          "threshold": 1.0,
          "name": "metric1",
          "metricName": "Heartbeat",
          "dimensions": [
            {
              "name": "Computer",
              "operator": "Include",
              "values": [
                "*"
              ]
            }
          ],
          "operator": "LessThan",
          "timeAggregation": "Total",
          "skipMetricValidation": false,
          "criterionType": "StaticThresholdCriterion"
        }
      ],
      "odata.type": "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria"
    },
    "autoMitigate": false,
    "actions": []
  }
}

DEBUG: AzureQoSEvent: Module: Az.Monitor:2.7.0; CommandName: Add-AzMetricAlertRuleV2; PSVersion: 5.1.19041.1023; IsSuccess: True; Duration: 00:00:
04.3043259
DEBUG: Finish sending metric.
DEBUG: 3:55:59 PM - AddAzureRmMetricAlertRuleV2Command end processing.
lijinpei2008 commented 2 years ago

Hi @rachaelsingleton, please run the script below to solve this issue you encounter.

$resourceGroupName="myResourceGroup-1231"
$workspaceName="myWorkSpace-1231"
$location="East US"
$shortName="agSN-1231"
$actionGroupName="actionGroupName-1231"

New-AzResourceGroup -Name $resourceGroupName -Location $location

New-AzOperationalInsightsWorkspace -ResourceGroupName $resourceGroupName -Name $workspaceName -Location $location

$workspace = get-azoperationalinsightsworkspace -ResourceGroupName $resourceGroupName -Name $workspaceName

$workspace | fl

$email1 = New-AzActionGroupReceiver -Name 'user1' -EmailReceiver -EmailAddress 'user1@example.com'

$sms1 = New-AzActionGroupReceiver -Name 'user2' -SmsReceiver -CountryCode '1' -PhoneNumber '5555555555'

Set-AzActionGroup -Name $actionGroupName -ResourceGroup $resourceGroupName -ShortName $shortName -Receiver $email1,$sms1

$ActionGroup = Get-AzActionGroup -ResourceGroup $resourceGroupName -Name $actionGroupName

$ActionGroup | fl

$metricTrigger = New-AzScheduledQueryRuleLogMetricTrigger -ThresholdOperator "GreaterThan" -Threshold 5 -MetricTriggerType "Consecutive" -MetricColumn "Computer"

$triggerCondition = New-AzScheduledQueryRuleTriggerCondition -ThresholdOperator "GreaterThan" -Threshold 3 -MetricTrigger $metricTrigger

$aznsActionGroup = New-AzScheduledQueryRuleAznsActionGroup -ActionGroup @($ActionGroup.ID) -EmailSubject "Email subject" -CustomWebhookPayload "{}"

$alertingAction = New-AzScheduledQueryRuleAlertingAction -AznsAction $aznsActionGroup -Severity "1" -Trigger $triggerCondition

$schedule = New-AzScheduledQueryRuleSchedule -FrequencyInMinutes 15 -TimeWindowInMinutes 15

$source = New-AzScheduledQueryRuleSource -Query "Heartbeat | summarize AggregatedValue = count() by bin(TimeGenerated, 5m)" `
                  -DataSourceId $workspace.ResourceId `
                  -QueryType "ResultCount"

New-AzScheduledQueryRule -ResourceGroupName $resourceGroupName `
                    -Location $location `
                    -Action $alertingAction `
                    -Name "Server Down Powershell" `
                    -Enabled $true `
                    -Schedule $schedule `
                    -Source $source `
                    -Description "Server Down Powershell"

Get-AzScheduledQueryRule -ResourceGroupName $resourceGroupName

OR

$resourceGroupName="myResourceGroup-1231"
$workspaceName="myWorkSpace-1231"
$location="East US"
$shortName="agSN-1231"
$actionGroupName="actionGroupName-1231"

New-AzResourceGroup -Name $resourceGroupName -Location $location

New-AzOperationalInsightsWorkspace -ResourceGroupName $resourceGroupName -Name $workspaceName -Location $location

$workspace = get-azoperationalinsightsworkspace -ResourceGroupName $resourceGroupName -Name $workspaceName

$workspace | fl

$email1 = New-AzActionGroupReceiver -Name 'user1' -EmailReceiver -EmailAddress 'user1@example.com'

$sms1 = New-AzActionGroupReceiver -Name 'user2' -SmsReceiver -CountryCode '1' -PhoneNumber '5555555555'

Set-AzActionGroup -Name $actionGroupName -ResourceGroup $resourceGroupName -ShortName $shortName -Receiver $email1,$sms1

$ActionGroup = Get-AzActionGroup -ResourceGroup $resourceGroupName -Name $actionGroupName

$ActionGroup | fl

$criteria = New-AzMetricAlertRuleV2Criteria -MetricName "Heartbeat" `
-DimensionSelection $dim `
-TimeAggregation Total `
-Operator LessThan `
-threshold 1

$criteria | fl

Add-AzMetricAlertRuleV2 -Name "Server Down Powershell" `
-Description "Server Down Powershell" `
-ResourceGroupName $resourceGroupName `
-WindowSize 0:5 `
-Frequency 0:1 `
-TargetResourceType "Microsoft.OperationalInsights/workspaces" `
-TargetResourceScope $workspace.ResourceId `
-TargetResourceRegion $location `
-Condition $criteria `
-ActionGroupId $ActionGroup.Id`
-Severity 0 `
-AutoMitigate $false

Get-AzMetricAlertRuleV2 -ResourceGroupName $resourceGroupName -Name "Server Down Powershell"

The alert rule type created with Add-AzMetricAlertRuleV2 is "metric-based alert rule" and must be queried by Get-AzMetricAlertRuleV2. The alert rule type created with New-AzScheduledQueryRule is "a log alert rule" and must be queried by Get-AzScheduledQueryRule. But when we update the item created by Add-AzMetricAlertRuleV2 on portal, we can query the details either using Get-AzMetricAlertRuleV2 or using Get-AzScheduledQueryRule. Thank you for your help.

ghost commented 2 years ago

Hi, we're sending this friendly reminder because we haven't heard back from you in a while. We need more information about this issue to help address it. Please be sure to give us your input within the next 7 days. If we don't hear back from you within 14 days of this comment the issue will be automatically closed. Thank you!