среда, 31 октября 2018 г.

User account blocking for 100 days is not logged and mailbox not used for another actions (full access/forward mails)

#by me ;)

import-module activedirectory
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn;

$LOGFILE="c:\scripts\aduserblock1.log"
$SMTPSERVER = "mail.domain.local"

function log([string]$txt)
{ add-content $LOGFILE "$(Get-date): $txt" }


function SendEmaiToSD($msgstr){
Send-MailMessage -From powershell@domain.local -To sd@domain.local -Subject "Скрипт блокировки учетных записей в домене domain.loc вызвал ошибку выполнения." -Body $($msgstr) -SmtpServer $SMTPSERVER -Priority High -Encoding UTF8
}

function main{
$mdate = (Get-date).Add(-100d)
$oldusers = get-aduser -Filter {Enabled -eq $true -and msExchMailboxGuid -like "*"} -properties samaccountname, lastlogondate | where{$_.samaccountname -match "^\w{1,2}\.\w+$" -and $_.LastLogonDate -lt $mdate -and $_.LastLogonDate -ne $null} | sort-object lastlogondate | select samaccountname, lastlogondate

foreach($user in $oldusers){
$userIdentities = @()
$usermailbox = get-mailbox -Identity $($user.samaccountname)
if($usermailbox.ForwardingAddress -ne $null){
#write-host detected Forward for $user.samaccountname
continue
}
foreach($userSecurityIdentifier in ($usermailbox | get-mailboxpermission | ?{$_.IsInherited -eq $false -and $_.user -notlike "*NT*AUTH*"}).User.SecurityIdentifier.Value){
if($userSecurityIdentifier -eq $null){
continue
}
$adobject = get-adobject -Filter 'objectSID -like $userSecurityIdentifier -and ObjectClass -eq "user"'
$userIdentities+=$adobject
}
if($userIdentities.Count -gt 0){
#write-host User  $user.samaccountname has another owners for mailbox lastlogondate=$user.lastlogondate
continue
}
log("User account "+$user.samaccountname+" Disabled")
Set-ADUser -Identity $user.samaccountname -Enabled $false
}
}

try{
main
}
catch
{
$ErrorMessage = $_.Exception.Message
SendEmaiToSD($ErrorMessage)
}