How to separate "known" output from script to email

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

are these “known” accounts always hard-coded in your query?

if so, why can’t you just add to $body prior to the send-mailmessage?
something like this?
foreach ($account in $accounts) {
$body = $body + $account.name + “`r`n”}
$body = $body + “Known Account 'r’n NDR ACCOUNT 'r’n Johnny Appleseed”

Well, you could define them as variables and pass them to the body also…
$NDRacc = “NDR Account”
in the filter then: -notlike “CN=$NDRacc*”
and pretty much the same with $body

that is probably the best approach, Rocky, just write another query before the output, reverse all of your -notlike to -like

then you can insert those into the body of your email just like you are doing for the accounts that you want returned