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

Azure AD客户端密钥状态判断异常,IF语句始终进入过期分支求助

问题原因及修复方案

核心错误1:属性名不匹配

在Select-Object步骤中,你将EndDateTime重命名为了EndDate,但后续判断状态时仍使用原属性名$_.EndDateTime。由于新对象中不存在EndDateTime属性,其值为$null,而$null与任何日期比较都会被判定为“小于”,导致所有密钥都被标记为Expired。

核心错误2:日期格式与UTC一致性(可选验证)

Azure AD返回的EndDateTime是UTC时间,你的$today已转换为UTC,但需确保EndDate的类型是DateTime而非字符串。若EndDateTime返回的是字符串格式(如20.10.2022 9.29.56),需手动指定格式转换,避免因系统区域设置差异导致解析错误。

修复后的脚本

Write-Host 'Gathering necessary information...'
$applications = Get-AzADApplication
$servicePrincipals = Get-AzADServicePrincipal

$appWithCredentials = @()
$appWithCredentials += $applications | Sort-Object -Property DisplayName | ForEach-Object {
    $application = $_
    $sp = $servicePrincipals | Where-Object ApplicationId -eq $application.ApplicationId
    Write-Verbose ('Fetching information for application {0}' -f $application.DisplayName)
    $application | Get-AzADAppCredential -ErrorAction SilentlyContinue | Select-Object -Property @{Name = 'DisplayName'; Expression = { $application.DisplayName } }, 
        @{Name = 'ObjectId'; Expression = { $application.Id } }, 
        @{Name = 'ApplicationId'; Expression = { $application.ApplicationId } }, 
        @{Name = 'KeyId'; Expression = { $_.KeyId } }, 
        @{Name = 'Type'; Expression = { $_.Type } }, 
        @{Name = 'StartDate'; Expression = { [datetime]::Parse($_.StartDate, [cultureinfo]::GetCultureInfo('de-DE')) } }, # 适配日.月.年格式
        @{Name = 'EndDate'; Expression = { [datetime]::Parse($_.EndDateTime, [cultureinfo]::GetCultureInfo('de-DE')).ToUniversalTime() } }
}

Write-Host 'Validating expiration data...'
$today = (Get-Date).ToUniversalTime()
$limitDate = $today.AddDays(30)
$appWithCredentials | Sort-Object EndDate | ForEach-Object {
    # 使用重命名后的EndDate属性判断
    if ($_.EndDate -lt $today) {
        $_ | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Expired'
    }
    elseif ($_.EndDate -le $limitDate) {
        $_ | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'ExpiringSoon'
    }
    else {
        $_ | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Valid'
    }
}

关键修复点说明

  • 将状态判断中的$_.EndDateTime改为$_.EndDate,与前面的属性重命名保持一致。
  • 显式指定日期解析的文化格式(如de-DE对应日.月.年),避免区域设置导致的解析错误,并转换为UTC时间,确保与$today的时区一致。
  • 若Get-AzADAppCredential返回的EndDateTime已经是DateTime类型,可去掉[datetime]::Parse部分,直接保留$_.EndDateTime.ToUniversalTime()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:10:36