You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Azure函数应用中用PowerShell脚本触发告警并传递结果?

在Azure函数应用中用PowerShell触发Azure Alert并传递执行结果

可以实现。以下是具体的实现思路和修改后的脚本:

核心逻辑说明

Azure Alert通常基于监控指标或日志触发,但也可以通过Azure Monitor API直接触发自定义警报,或是利用Action Group直接发送包含自定义内容的通知。在Azure Functions的PowerShell环境中,你可以将$res的执行结果格式化后,通过API传递给Alert或直接通过Action Group发送邮件。

步骤与示例脚本

1. 准备工作

确保Azure Functions的PowerShell环境已安装Az.Monitor和Az.Accounts模块(若未预装,需在函数的requirements.psd1中添加这两个模块的版本声明)。同时,给函数的托管标识分配Monitoring Contributor权限,用于调用Azure Monitor相关API。

2. 修改后的脚本示例

# 获取资源组并格式化结果为易读格式
$res = Get-AzResourceGroup
# 转为JSON格式保留完整结构,也可用Format-Table -AutoSize | Out-String转为表格文本
$formattedRes = $res | ConvertTo-Json -Depth 10

# 若已存在Action Group,直接获取即可,无需重复创建
$actionGroup = Get-AzActionGroup -Name "notify-admins" -ResourceGroupName "test-group"

# 获取访问令牌用于调用Azure Monitor API
$context = Get-AzContext
$token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate(
    $context.Account, 
    $context.Environment, 
    $context.Tenant.Id.ToString(), 
    $null, 
    [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, 
    $null, 
    "https://monitor.azure.com"
).AccessToken

# 替换为你的订阅ID和自定义警报规则名称
$subscriptionId = "你的订阅ID"
$alertRuleName = "自定义资源组查询警报"
$alertTriggerUri = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/test-group/providers/Microsoft.Insights/metricAlerts/$alertRuleName/activate?api-version=2018-03-01"

# 构造包含执行结果的警报触发请求体
$requestBody = @{
    status = "Activated"
    context = @{
        timestamp = (Get-Date).ToUniversalTime().ToString("o")
        description = "资源组查询任务执行完成,结果如下:"
        customPayload = @{
            ResourceGroups = $formattedRes
        }
    }
} | ConvertTo-Json -Depth 10

# 触发警报
Invoke-RestMethod -Uri $alertTriggerUri -Method Post -Headers @{"Authorization" = "Bearer $token"} -Body $requestBody -ContentType "application/json"

替代方案:直接通过Action Group发送自定义邮件

如果不需要创建完整的警报规则,也可以直接调用Action Group的Webhook接收器,发送包含$res结果的邮件:

  • 在Action Group中添加一个Webhook接收器
  • 用Invoke-RestMethod直接向Webhook地址发送包含$res内容的请求,配合逻辑应用可以更灵活地格式化邮件内容

注意事项

  • 确保自定义警报规则已关联目标Action Group(即你创建的notify-admins)
  • 邮件中要展示自定义Payload内容,需在Action Group的邮件设置中启用“包含自定义Payload”选项
  • 若使用托管标识,需确保其权限覆盖目标资源组和警报规则的操作范围

内容的提问来源于stack exchange,提问作者Korman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 15:35:29