Thank you Wei-Yen. I’ll try that out.
I actually found another way but the OU I’m referencing has sub-OUs that contain service or shared accounts that where created in Office 365 for a special purpose but never get logged on - so far script only identified 1 account.
My manager know wants to see those “known” or “whitelisted” accounts displayed in the email under a heading “Known accounts” or “White listed accounts”
But, not sure how to go about scripting that. I don’t know if I can do another “ELSE” statement.
Here is the script that’s currently running:
######################################################################
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, Special and NDR account.
#######################################################################
$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*”}
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 the “NDR account” from being reported on. How can I still report that known account in the email under a heading “Known accounts” in the body of the email?
Thanks.