I am trying to make an automated script that once a month will send an email to our companys managers about externals working in their departments about their accounts expiring.
I have made this, but when it has directreports in the top it wont send any emails, when i change them to manager i also have to change the to address but then i get the correct e-mail at least.
Get-ADUser -Filter * -SearchBase '' -Properties Manager,DirectReports,EmailAddress,Displayname | ForEach {
$ManagerName = $_.Displayname
$body = @()
If ($_.directreports) {
$managerEmailAddress = $_.EmailAddress
$_.directreports | ForEach {
$userDetails = Get-ADUser -Filter * -SearchBase '' -Properties AccountExpirationDate
If ( $userDetails.AccountExpirationDate ) {
If (($userDetails.AccountExpirationDate -lt (Get-Date).AddDays(30)) -and
($userDetails.AccountExpirationDate -ge (Get-Date))) {
$sendEmail = $true
$props = [ordered]@{
Username=$userDetails.SamAccountName
'Account Expiration Date'=$userDetails.AccountExpirationDate
}
$body += New-Object PsObject -Property $props
}
}
}
}
If ($sendEmail) {
$body = $body | Out-String
Send-MailMessage -From 'mail@company.com' -To $managerEmailAddress -Subject 'Account Expiration Report' -Body $body -SmtpServer 'smtp server'
}
$sendEmail = $false
}