今天早上朋友问我如何获取指定某个时间段的AD用户登录时间和相关的邮箱登录时间。


豆子公司的Exchange已经转移到Office365上,首先远程的导入AD模块,本地导入MSOnline的模块,这样我就可以远程访问AD和Office365了


下面是一个例子,判断90天没有登录的AD账号,并把其中30天没有登陆邮箱的账号都找出来


# 导入AD模块
$s= New-PSSession -ComputerName "syddc01"
Invoke-Command -Session $s {Import-Module activedirectory}
Import-PSSession -Session $s -Module activedirectory 

#导入MSOnline模块
$cred = Get-Credential "yli@syd.ddb.com"
Import-Module MSOnline
Set-ExecutionPolicy remotesigned
Connect-MsolService -Credential $cred

#连接到Office365
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell/ -Credential $Cred -Authentication Basic -AllowRedirection
Import-PSSession $session


$when1=((get-date).AddDays(-90)).Date
$when2=((get-date).AddDays(-30)).Date

#获取90天内未登陆的账号信息
$users=get-aduser -Filter {(lastlogontimestamp -like '*') -and (emailaddress -like '*')} -Properties * | select name, lastlogontimestamp, @{n="Logon";e={[datetime]::FromFileTime($_.lastlogontimestamp.tostring())}} | Where-Object {$_.Logon -lt $when1}

#获取其中30天未登录邮箱的账号信息
foreach($user in $users){
if($a=Get-Mailbox $user.Name -ErrorAction SilentlyContinue ){
$a | get-mailboxstatistics | Where-Object { $_.lastlogontime -lt $when2} | select displayname,lastlogontime 
}
}

结果如下

wKiom1YkfLHxU10eAADQ_BC3IbQ335.jpg


这只是一个测试的脚本,验证一下思路,并不完善,比如信息的过滤可以考虑用filter 而不是where-object;缺少异常处理,用户登录账号加密,后期自动发送结果给管理员,缺少参数化等等;如果需要的话可以慢慢进行优化处理。