如何用PowerShell获取用户近30天最后登录记录(仅能获取24小时)
解决PowerShell获取用户近30天最后登录记录的问题
你的核心需求是获取用户近30天内的最后登录日志,当前脚本仅能获取24小时数据,主要问题出在日期格式处理和Graph API筛选语法上,以下是修正方案:
关键问题分析
- 日期格式不符合Graph API要求:原脚本中日期转换后的格式没有用单引号包裹,Graph的OData筛选器要求日期字符串必须用单引号括起来。
- 日期范围计算不够精准:
AddMonths(-1)会取整月(比如31天),如果需要严格30天,应该用AddDays(-30)。 - 混用AzureAD和Graph模块:同时调用
Connect-AzureAD和Connect-MgGraph没必要,统一用Microsoft Graph模块更简洁。
修正后的完整脚本
Import-Module Microsoft.Graph.Reports # 连接Microsoft Graph,确保已授权所需权限 Connect-MgGraph -Scopes "AuditLog.Read.All", "User.Read.All" # 从文本文件读取用户列表 $users = Get-Content "$Env:USERPROFILE\Desktop\list.txt" # 定义近30天的起始日期(转换为UTC格式) $dateRange = (Get-Date).AddDays(-30).ToUniversalTime() $filterDate = $dateRange.ToString("yyyy-MM-ddTHH:mm:ssZ") $results = foreach ($user in $users) { # 使用Graph模块获取用户信息,替代Get-AzureADUser $userOutput = Get-MgUser -UserId $user -Property DisplayName, UserPrincipalName, AccountEnabled, EmployeeId | Select-Object DisplayName, UserPrincipalName, AccountEnabled, EmployeeId if ($userOutput) { # 修正Filter语法:日期字符串加单引号,确保Graph能正确解析 $signInLogs = Get-MgAuditLogSignIn -All -Filter "userPrincipalName eq '$user' and createdDateTime ge '$filterDate'" | Sort-Object createdDateTime -Descending $lastSignIn = if ($signInLogs) { # 转换为目标时区(此处保留原脚本的减4小时逻辑,可根据实际需求调整) $signInLogs[0].CreatedDateTime.AddHours(-4).ToString("MMM dd, yyyy, h:mm tt") } else { "Never" } Write-Host "用户信息: $($userOutput.DisplayName) | $($userOutput.UserPrincipalName) | 最后登录: $lastSignIn" [PSCustomObject]@{ DisplayName = $userOutput.DisplayName UserPrincipalName = $userOutput.UserPrincipalName EmployeeID = $userOutput.EmployeeId Enabled = $userOutput.AccountEnabled LastSignIn = $lastSignIn } } } # 导出结果到CSV文件 $results | Export-Csv -Path "$Env:USERPROFILE\Desktop\user_properties.csv" -NoTypeInformation
重要修改说明
- 统一使用Graph模块:用
Get-MgUser替代Get-AzureADUser,减少模块依赖,同时添加User.Read.All权限确保能读取用户基本信息。 - 日期格式修正:将日期转换为UTC格式后,用单引号包裹放入Filter中,确保Graph API能正确识别日期范围。
- 精准30天范围:用
AddDays(-30)替代AddMonths(-1),严格匹配近30天的需求。 - 权限补充:新增
User.Read.All权限,避免读取用户信息时出现权限不足的错误。
内容的提问来源于stack exchange,提问作者opperska
相关产品推荐
相关产品推荐

