Need help with how an e-mail outputs a variabel; it doesn't do it correctly.

Hello,

I’m in the process of working with a script that will check which users whose account has expired, ie has an expiration date that has passed. It should then deactivate the account and send an e-mail to the responsible manager and tell that now that the account of an employee you are responsible for has been deactivated and a decision needs to be made for what to do with their mailbox and other in Office 365. It is part of our off-boarding process so to speak :slight_smile:

However, have encountered a problem with the e-mail; the idea is that the manager in charge should get in his mail who / whom it applies, but I can not get that information in the mail. So need help with the part where it is printed in the mailing ticket which one or what employees it is.

It should add that I work with a script that I am not at all a father to, but have had to take over the work. I understand the logic of how it should work, but I don’t get it with the email formatting.

In the script, the following line applies which does not do what I want it to do:

$manEmp = $UserArray | foreach {if ({Get-ADUser (Get-ADUser $_. samaccountname -properties manager) .manager} -contains $manName) {$_. Name}}

The idea then is that the variable $manEmp should spit out all employees whose account that has been disabled and show for the person receiving the email is responsible for. After much searching and troubleshooting, I can’t figure out what that line should look like to get to it in the way it is intended.

Here comes the script in its entirety. The line I need help with (everything else is working as it should) is further down just before the “create the email section”:

### This script is for testing the off-boarding process. ### The PROBLEM right now in this script is to get the solution to send ONE mail PER Manager, and collect his employees from the list. (Instead of one email per USER ...).

### The MAIL TEXT is obviously not complete either.

# Email info
$SMTPserver = "smtp relay.domain.local"
$backupEmailAddress = "test@domain.se"
$mailFrom = "<employeeinfo@domain.se>"

# Basic info

### Regarding AddHours, this script means that everything that has been expired the last day is captured.
$Today = Get-Date
$OU = "OU = LAB Users, OU = LAB OU, DC = mtrs, DC = local"
$ExpTime = -12

# $UserArray = Search-ADAccount -SearchBase $OU -SearchScope 1 -AccountExpired -UsersOnly -resultSetSize $null | ? {$_. AccountExpirationDate -gt ($today). AddHours ($ExpTime)}
$UserArray = Search-ADAccount -SearchBase $OU -SearchScope 1 -AccountExpired -UsersOnly -ResultPageSize 2000 -resultSetSize $null

ForEach ($user in $UserArray)
{
    Disable-ADAccount -Identity $($user)
}
# View content (mostly for testing and troubleshooting now in the beginning)
# Write-Output Qty: $UserArray.Count
Write-Output $UserArray | ft Name, AccountExpirationDate, Enabled, manager

# Test for ForEach loop or equivalent (% = abbreviation for "ForEach").
# $Managers = $UserArray | % {Get-ADUser (Get-ADUser $_. Samaccountname -properties manager) .manager -properties emailaddress}
# $Managers | Select-Object Name, EmailAddress, SamAccountName

foreach ($manager in $Managers)
{
    #Get the manager info
    $manName = $manager.Name
    $manMail = $manager.emailaddress
    $manSAM = $manager.SamAccountName
    $today = Get-Date
    $manEmp = $UserArray | foreach {if ( {Get-ADUser (Get-ADUser $_. samaccountname -properties manager) .manager} -contains $manName) {$_. Name}}

    #Create email
    $mailSubject = "TESTMAIL !!: One of your employee accounts has been terminated."
    $mailBody = "

    <Html>
    
    <head> <meta http-equiv = "" Content-Type "" content = "" text / html; charset = utf-8 ""> </ head>
    
    <Body>
    
    <p>  An English version of this email can be found further down  </p>
    
    <p> Hi $ manName, </p>
    
    <p> You will receive this message when one of your employees has left, and their primary account has now been closed. </p>
    
    

Who and why?

<p> Below you can see which one (s) apply. As a responsible person, you have to decide what happens to parts of their digital content. Applies to Mailbox and OneDrive </p> <p> This email is as follows: </p> $manEmp <p> Thank you for your cooperation! Have a nice evening. Contact the IT Support for questions or help </p> <br/> <p> Hi $ manName, </p> <p> Translate above into english. </p> </ Body> </ Html> " if ($manMail -eq $null) { $mailSendTo = $backupEmailAddress } else { $mailSendTo = $manMail # In this mode, it sends ONE mail to managers for each user. A manager can thus receive several emails ... Send-MailMessage -SmtpServer $smtpServer -From $mailFrom -To $mailSendTo -Subject $mailSubject -Body $mailBody -bodyasHTML -priority High -Encoding UTF8 -ErrorAction Stop } }

I am grateful for all the help I can get with this! Am sorry if it is long and hard to read or if it is the wrong forum to ask in, say so I am looking for further.

A couple things to suggest:

  1. You can simplify $manEmp to this (no need for double-call of Get-ADUser):
    $manEmp = $UserArray | ForEach-Object {
        if ((Get-ADUser -Identity $_.SamAccountName -Properties Manager).Manager -match $manName) {
            Write-Output $_.Name
        }
    }
  2. If $manEmp is not empty, you can try this for name output:
    ...
    This email is as follows:
    

    ($manEmp | Out-String)


    or:

    ...
    This mail is as follows:
    
    ($manEmp -join "`n")

You may want to consider including the users’ SamAccountName/UserPrincipalName in the email so that managers can identify accounts for offboarding more accurately than just referencing the Name/DisplayName.

Personally, I would gather all of the information with Get-ADuser rather than using Search-ADAccount. Next, rather than send multiple emails to a manager, you may want to consider grouping users which works for 1 or 100 users, but the manager gets a single email. Here is some code to play with:

$today = Get-Date
$user = Get-AdUser -Filter {(Enabled -eq $True) -and (AccountExpirationDate -lt $Today)} -Properties Manager, AccountExpirationDate | 
        Select Name, 
               SamAccountName, 
               Manager,
               AccountExpirationDate,
               Enabled,
               @{Name='ManagerName';Expression={Get-ADUser -Identity $_.Manager -Properties DisplayName | Select -ExpandProperty DisplayName}},
               @{Name='ManagerSamAccountName';Expression={Get-ADUser -Identity $_.Manager -Properties SamAccountName | Select -ExpandProperty SamAccountName}},
               @{Name='ManagerEmail';Expression={Get-ADUser -Identity $_.Manager -Properties Mail | Select -ExpandProperty Mail}}



foreach ($manager in ($user | Group-Object -Property ManagerEmail)) {
    $expiredUsers = $manager.Group | Select Name, SamAccountName, AccountExpirationDate
    $expiredUsersHtml = $expiredUsers | ConvertTo-Html -Fragment -As Table
    

$body = @"
<html>
    <head>
    </head>
    <body>
        The following users were expired and have been disabled:

        $expiredUsersHtml
    </body>
</html>

"@


$body

    #ManagerEmail was used to group, so we reference it by 'Group' Name
    #Send-MailMessage -To $manager.Name -Body ($body | Out-String) -BodyAsHtml

}