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

如何编写查询语句获取近30天未登录的有效Azure用户列表?

可行实现方案

方案1:Log Analytics KQL查询(推荐)

前提:你已经提前将Azure AD登录日志同步到了Log Analytics工作区,该方案可以直接运行查询秒出结果。
查询语句如下:

// 提取过去30天有成功登录记录的用户ID集合
let activeUsers = SigninLogs
| where TimeGenerated >= ago(30d)
| where Status.ErrorCode == 0
| distinct UserId;
// 匹配所有活跃未删除、且不在上述登录集合中的用户
AADUsers
| where AccountEnabled == true
| where IsDeleted == false
| where UserId !in (activeUsers)
| project UserPrincipalName, DisplayName, Department, JobTitle, CreatedDateTime, LastPasswordChangeDateTime

逻辑说明:

  • 第一步先过滤过去30天内所有成功的登录记录,去重得到所有有登录行为的用户ID
  • 第二步匹配全量Azure AD用户,过滤掉已禁用、已删除的账号,排除有登录记录的用户,剩下的就是符合要求的用户列表
  • 你可以根据需求调整project后的字段,导出你需要的用户属性

方案2:Microsoft Graph PowerShell 脚本查询

适合需要批量处理、或者没有配置Log Analytics日志同步的场景:

  1. 首先安装Microsoft Graph模块:
Install-Module Microsoft.Graph -Scope CurrentUser
  1. 运行查询脚本:
# 连接Microsoft Graph,申请所需权限
Connect-MgGraph -Scopes "User.Read.All","AuditLog.Read.All"

# 定义时间范围
$startDate = (Get-Date).AddDays(-30).ToString("yyyy-MM-dd")

# 获取过去30天有成功登录记录的用户ID
$activeUserIds = Get-MgAuditLogSignIn -Filter "createdDateTime ge $startDate and status/errorCode eq 0" | Select-Object -ExpandProperty UserId -Unique

# 获取所有活跃未删除的用户,过滤出没有登录记录的用户
Get-MgUser -Filter "accountEnabled eq true and deletedDateTime eq null" -All `
| Where-Object {$_.Id -notin $activeUserIds} `
| Select-Object UserPrincipalName, DisplayName, Department, JobTitle, CreatedDateTime

注意事项

  • 日志保留限制:Azure AD原生登录日志默认仅保留30天,如果你需要统计超过30天的登录数据,必须提前配置日志导出到Log Analytics或存储账号
  • 权限要求:执行上述查询的账号需要持有Azure AD的全局管理员、安全管理员或报告阅读者角色
  • 新创建用户过滤:如果需要排除创建时间不足30天的新用户,可以在查询条件中增加对CreatedDateTime的过滤,仅保留创建时间早于30天的用户

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:15:03