I have a script that queries Active Directory for all user accounts that have not logged on in past 30 days and sends an email with the output to IT dept.
I’ve been excluding “known” accounts ;such as, built-in Administrator and several “service accounts” in the script so they don’t constantly appear. But, IT dept would like to see a bottom heading called “Known Accounts” with the reoccurring ones never logged on and user accounts that match the query.
######################################################################
Please Configure the following variables…
$smtpServer=“mail”
$from = "Contoso IT "
$emailaddress = “italerts@Contoso.com”
$subject = “Contoso AD users that have not logged on in 30 days”
[string]$body = " "
#######################################################################
#Find all AD users that have not logged on in 30 days.
#######################################################################
#The SEARCHBASE starts in “OU=Accounts” but excludes the following OUs:
#Service, Shared, Inactive and Special.
#######################################################################
$accounts = Search-ADAccount -AccountInactive -UsersOnly -TimeSpan 30.00:00:00 -SearchBase “OU=Accounts,DC=HQ,DC=Contoso,DC=Com” | ? {$.DistinguishedName -notlike “OU=Services,OU=Accounts,” -and $.DistinguishedName -notlike “OU=Shared,OU=Accounts,” -and $.DistinguishedName -notlike “OU=Inactive,OU=Accounts,” -and $.DistinguishedName -notlike “OU=Special,OU=Accounts,” -and $.DistinguishedName -notlike “CN=NDR Account*” -and $.DistinguishedName -notlike “CN=Johnny Appleseed*”}
If ($accounts -eq $null) {
Send-Mailmessage -smtpServer $smtpServer -from $from -to $emailaddress -subject $subject -Body “No users found.” -priority High
}
Else {
foreach ($account in $accounts) {
$body = $body + $account.name + “`r`n”}
Send-Mailmessage -smtpServer $smtpServer -from $from -to $emailaddress -subject $subject -Body $body -priority High
In the above script, I’m excluding “NDR Account” and “Johnny Appleseed”. How can add them under the heading “Known accounts” in the body of the email?
Example,
Received email:
Users
Joe Grant
Mary Sizemoore
Known Accounts
NDR Account
Johnny Appleseed