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

PowerShell脚本Teams告警空表问题求助:过期应用凭据检测

修复应用密钥/证书过期Teams告警脚本的空表格问题

检测脚本已能正确抓取30天内即将过期的应用注册密钥和证书信息,但配套的Teams告警脚本发送的消息表格始终为空,核心问题及修复方案如下:

问题根源

  1. 属性名错误:告警脚本中Select-Object误用了循环临时变量$AppName、$RemainingDaysCount,而$Logs对象的实际属性为ApplicationName、ExpiresInDays,导致无法提取有效数据
  2. 变量未定义:标题中引用未初始化的$Array变量,且存在拼写错误areExpiring
  3. HTML格式不兼容:ConvertTo-Html生成完整HTML文档,Teams MessageCard不支持多余的HTML头部/尾部

修复方案1:修正HTML表格提取

# 从$Logs中选择需要展示的字段,使用正确的属性名
$selectedData = $Logs | Select-Object ApplicationName, ApplicationID, `
    @{Name='凭据名称'; Expression={$_.SecretName ?? $_.CertificateName}}, `
    @{Name='过期日期'; Expression={$_.SecretEndDate ?? $_.CertificateEndDate}}, `
    ExpiresInDays, Owner

# 转换为HTML片段(仅保留表格部分)
$htmlTable = $selectedData | ConvertTo-Html -Fragment

# 构建Teams MessageCard
$JSONBody = [PSCustomObject][Ordered]@{
    "@type"      = "MessageCard"
    "@context"   = "http://schema.org/extensions"
    "themeColor" = 'FFCC00' # 黄色警示色更醒目
    "title"      = "$($Logs.Count) 个应用密钥/证书即将过期"
    "text"       = "以下是30天内即将过期的应用凭据信息:<br/>$htmlTable"
}

$TeamMessageBody = ConvertTo-Json $JSONBody -Depth 5
$parameters = @{
    "URI"         = '你的Teams Webhook URI'
    "Method"      = 'POST'
    "Body"        = $TeamMessageBody
    "ContentType" = 'application/json'
}
Invoke-RestMethod @parameters

修复方案2:使用MessageCard原生Sections表格(推荐)

该方案在Teams中显示更规范,支持结构化字段展示:

# 构建表格行数据
$tableSections = foreach ($item in $Logs) {
    $credName = $item.SecretName ?? $item.CertificateName
    $expiryDate = $item.SecretEndDate ?? $item.CertificateEndDate
    @{
        "facts" = @(
            @{ "name" = "应用名称"; "value" = $item.ApplicationName },
            @{ "name" = "应用ID"; "value" = $item.ApplicationID },
            @{ "name" = "凭据名称"; "value" = $credName },
            @{ "name" = "过期日期"; "value" = $expiryDate.ToString("yyyy-MM-dd") },
            @{ "name" = "剩余天数"; "value" = "$($item.ExpiresInDays) 天" },
            @{ "name" = "负责人"; "value" = $item.Owner }
        )
        "text" = ""
    }
}

# 合并为最终MessageCard
$JSONBody = [PSCustomObject][Ordered]@{
    "@type"      = "MessageCard"
    "@context"   = "http://schema.org/extensions"
    "themeColor" = 'FFCC00'
    "title"      = "$($Logs.Count) 个应用密钥/证书即将过期"
    "text"       = "检测到以下应用的凭据将在30天内过期,请及时更新:"
    "sections"   = $tableSections
}

$TeamMessageBody = ConvertTo-Json $JSONBody -Depth 10
$parameters = @{
    "URI"         = '你的Teams Webhook URI'
    "Method"      = 'POST'
    "Body"        = $TeamMessageBody
    "ContentType" = 'application/json'
}
Invoke-RestMethod @parameters

额外优化建议

  • 检测脚本中Get-MgApplicationOwner可提前缓存,避免重复调用提升执行效率
  • 可根据剩余天数设置不同主题色(如剩余7天内用红色),区分紧急程度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:07:32