PowerShell脚本开发求助:获取用户交互式登录属性及规则判断
完善Azure AD用户交互式登录检测PowerShell脚本
需求概述
- 从Azure AD用户数据中提取以下核心属性:
Last interactive sign in (UTC):用户最后一次交互式登录的UTC时间Last interactive sign in (user local time):转换为用户本地时区的最后交互式登录时间Last App:最后一次交互式登录对应的应用名称
- 实现判断逻辑:检查用户是否在上一个工作日(全球员工周末为周五、周六)的00:00-23:59期间未进行交互式登录
- 输出固定格式的内容,字段顺序为:
ErrorNumber,UPN,date,Service Provider,Country,City,Error,Last interactive sign in (UTC),Last interactive sign in (user local time),Last App
完整代码实现
# 初始化错误编号计数器 $errorNumber = 1 # 计算上一个工作日(适配周五、周六为周末的规则) $today = Get-Date switch ($today.DayOfWeek) { 'Sunday' { $lastWorkDay = $today.AddDays(-2) } 'Monday' { $lastWorkDay = $today.AddDays(-3) } default { $lastWorkDay = $today.AddDays(-1) } } # 定义上一个工作日的时间区间:00:00 到 23:59 $startOfLastWorkDay = Get-Date -Date $lastWorkDay -Hour 0 -Minute 0 -Second 0 $endOfLastWorkDay = Get-Date -Date $lastWorkDay -Hour 23 -Minute 59 -Second 59 # 假设已通过Get-MgUser等命令获取Azure AD用户集合(需提前连接Microsoft Graph) foreach ($User in $AzureADUsers) { $upn = $User.UserPrincipalName $company = $User.companyName $country = $User.Country $city = $User.City $err = $null $lastInteractiveUtc = $null $lastInteractiveLocal = $null $lastApp = $null # 仅处理目标公司用户 if ($company -eq 'company1') { # 处理SignInActivity为空的场景 if ($null -eq $User.SignInActivity) { $err = "No interactive sign in detected" } else { # 获取最后一次交互式登录记录 $interactiveSignIn = $User.SignInActivity.Interactive if ($null -eq $interactiveSignIn) { $err = "No interactive sign in detected" } else { # 提取UTC登录时间和应用名称 $lastInteractiveUtc = $interactiveSignIn.LastSignInDateTime $lastApp = $interactiveSignIn.LastSignInDisplayName # 转换为用户本地时间(优先使用用户邮箱设置的时区,无则保留UTC) if ($User.MailboxSettings.TimeZone) { $timeZone = [System.TimeZoneInfo]::FindSystemTimeZoneById($User.MailboxSettings.TimeZone) $lastInteractiveLocal = [System.TimeZoneInfo]::ConvertTimeFromUtc($lastInteractiveUtc, $timeZone) } else { $lastInteractiveLocal = $lastInteractiveUtc } # 判断是否在上一个工作日区间内有登录 if ($lastInteractiveUtc -lt $startOfLastWorkDay -or $lastInteractiveUtc -gt $endOfLastWorkDay) { $err = "No interactive sign in during last workday ($($lastWorkDay.ToString('yyyy-MM-dd')))" } } } # 按指定格式输出(如需写入文件,可替换为Export-Csv -Append) if ($err) { "$errorNumber,$upn,$($lastWorkDay.ToString('yyyy-MM-dd')),$company,$country,$city,$err,$lastInteractiveUtc,$lastInteractiveLocal,$lastApp" $errorNumber++ } } }
代码关键说明
- 工作日计算:通过
switch语句根据当前日期动态计算上一个工作日,适配周五、周六为周末的特殊规则 - 属性提取逻辑:
Last interactive sign in (UTC):直接从$User.SignInActivity.Interactive.LastSignInDateTime提取原始UTC时间Last interactive sign in (user local time):利用用户邮箱配置的时区信息转换UTC时间,若时区缺失则默认保留UTC时间Last App:从$User.SignInActivity.Interactive.LastSignInDisplayName获取登录应用名称
- 登录时间校验:对比最后一次交互式登录的UTC时间是否落在上一个工作日的00:00-23:59区间内
- 输出控制:仅当检测到符合条件的异常时输出内容,严格遵循需求指定的字段顺序
内容的提问来源于stack exchange,提问作者az_mhb
相关产品推荐
相关产品推荐

