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

如何编写ForEach-If循环检测Azure Application Proxy证书30天内到期状态

Azure Application Proxy 证书临期检测脚本修改方案

核心调整说明

你只需要在原有遍历应用的循环中增加有效期判断逻辑,同时新增一个数组存储临期证书即可实现需求,具体修改如下:

完整可运行脚本

$aadapServPrinc = Get-AzureADServicePrincipal -Top 100000 | Where-Object {$_.Tags -Contains "WindowsAzureActiveDirectoryOnPremApp"}  
$allApps = Get-AzureADApplication -Top 100000 
$aadapApp = $aadapServPrinc | ForEach-Object { $allApps -match $_.AppId} 

Write-Host "Displaying all custom domain Azure AD Application Proxy applications and the uploaded certificates..." -BackgroundColor "Black" -ForegroundColor "Green"
Write-Host " "

# 初始化存储数组,可自定义临期阈值
$allCerts = @()
$expiringCerts = @()
$expireThreshold = 30

foreach ($item in $aadapApp) { 
    $tempApps = Get-AzureADApplicationProxyApplication -ObjectId $item.ObjectId
    $certMeta = $tempApps.VerifiedCustomDomainCertificatesMetadata
    
    # 跳过无有效自定义域名证书的应用
    if (-not $certMeta -or $certMeta -match "class") {
        continue
    }

    # 加入全量证书列表
    $allCerts += $certMeta

    # 临期判断逻辑
    try {
        [DateTime]$expiryDate = $certMeta.ExpiryDate
        $daysRemaining = ($expiryDate - (Get-Date)).TotalDays
        # 剩余天数不足30天即判定为临期,若需要排除已过期证书可添加条件 && $daysRemaining -gt 0
        if ($daysRemaining -lt $expireThreshold) {
            # 追加剩余天数字段便于查看
            $certMeta | Add-Member -NotePropertyName "DaysRemaining" -NotePropertyValue ([math]::Round($daysRemaining,2)) -Force
            $expiringCerts += $certMeta
        }
    }
    catch {
        Write-Warning "应用 $($item.DisplayName) 证书到期时间解析失败,跳过检测"
    }
}  

# 输出全量在用证书
Write-Host "`n=== 所有在用证书 ===" -ForegroundColor Green
$allCerts | Sort-Object Thumbprint | Get-Unique | Format-List *

# 输出临期证书
Write-Host "`n=== 临期证书(距到期不足 $expireThreshold 天) ===" -ForegroundColor Red
if ($expiringCerts.Count -eq 0) {
    Write-Host "当前无临期证书" -ForegroundColor Green
}
else {
    $expiringCerts | Sort-Object DaysRemaining | Format-List *
}

逻辑说明

  • 遍历每个应用代理应用时先过滤掉无有效证书的记录,避免无效判断
  • 增加异常捕获逻辑,避免证书到期时间格式异常导致脚本中断
  • 时间差计算直接使用DateTime类型相减即可,无需单独调用New-TimeSpan
  • 临期证书额外追加剩余天数字段,优先级按到期时间从近到远排序展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:36:03