如何筛选90天未登录的AD用户?基于Get-LastLogon的过滤方法
获取90天未登录的Active Directory用户并添加过滤条件
要筛选出90天未登录的用户,你需要先计算90天前的基准日期,再对获取到的$LogonDate进行判断——要么用户从未登录(返回"Never"),要么最后登录时间早于这个基准日期。以下是修改后的完整脚本和关键改动说明:
关键改动点
- 先计算90天前的日期作为过滤阈值:
$90DaysAgo = (Get-Date).AddDays(-90)
- 在
ForEach-Object中添加判断逻辑,只保留符合条件的用户:- 处理
$LogonDate为"Never"的情况(从未登录) - 处理
$LogonDate为日期对象的情况,判断是否早于$90DaysAgo
- 处理
修改后的完整脚本
Function Get-LastLogon (){ [cmdletbinding()] Param( [alias("UserName","User","SamAccountName","Name","DistinguishedName","UserPrincipalName","DN","UPN")] [parameter(ValueFromPipeline,Position=0,Mandatory)] [string[]]$Identity ) begin{ $DCList = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers.name } process{ foreach($currentuser in $Identity) { $filter = switch -Regex ($currentuser){ '=' {'DistinguishedName';break} '@' {'UserPrincipalName';break} ' ' {'Name';break} default {'SamAccountName'} } Write-Verbose "Checking lastlogon for user: $currentuser" foreach($DC in $DCList) { Write-Verbose "Current domain controller: $DC" $ad = [ADSI]"LDAP://$dc" $searcher = [DirectoryServices.DirectorySearcher]::new($ad,"($filter=$currentuser)") $account = $searcher.findone() if(!$account) { Write-Verbose "No user found with search term '$filter=$currentuser'" continue } $logon = $($account.Properties.lastlogon) $logontimestamp = $($account.Properties.lastlogontimestamp) Write-Verbose "LastLogon : $([datetime]::FromFileTime($logon))" Write-Verbose "LastLogonTimeStamp : $([datetime]::FromFileTime($logontimestamp))" $logontime = $($logon,$logontimestamp | Sort-Object -Descending | Select-Object -First 1) if($logontime -gt $newest) { $newest = $logontime } } if($account) { switch ([datetime]::FromFileTime($newest)){ {$_.year -eq '1600'}{ "Never" } default{$_} } } Remove-Variable newest,account,logon,logontime,logontimestamp -ErrorAction SilentlyContinue } } end{ Remove-Variable dclist -ErrorAction SilentlyContinue } } # 导入ActiveDirectory模块 if (-not (Get-Module ActiveDirectory)){ Import-Module ActiveDirectory -ErrorAction Stop } # 计算90天前的基准日期 $90DaysAgo = (Get-Date).AddDays(-90) # 获取所有AD用户并筛选90天未登录的用户 Get-ADUser -Filter * -Properties DisplayName, Enabled | ForEach-Object { $LogonDate = Get-LastLogon -Identity $_.SamAccountName # 判断是否符合90天未登录或从未登录的条件 $isInactive = $false if ($LogonDate -eq "Never") { $isInactive = $true } elseif ($LogonDate -is [datetime] -and $LogonDate -lt $90DaysAgo) { $isInactive = $true } if ($isInactive) { [PsCustomObject]@{ 'Account Status' = if ($_.Enabled) {'Enabled'} Else {'Disabled'} 'Display Name' = $_.DisplayName 'Last Logon Time' = $LogonDate } } } | Export-Csv -Path 'C:\tmp\inactive_users_lastlogon.csv' -NoTypeInformation -Encoding UTF8
额外说明
- 原脚本中
Get-ADUser指定了-identity "user",修改为-Filter *以获取所有用户 - 去掉了
-Properties *,只加载需要的DisplayName和Enabled属性,提升执行效率 - 处理了
$LogonDate的两种返回类型:字符串"Never"和日期对象,确保过滤逻辑覆盖所有情况
内容的提问来源于stack exchange,提问作者Arbelac
相关产品推荐
相关产品推荐

