简体   繁体   中英

How would I send an email to myself if the user's manager field is empty in AD?

Hello I am new to PowerShell and I am trying to figure out how to send emails to user's manager. In the script below I am able to send the notification if in AD,manager field is not empty, but when is black I get an error message. How do I make it where it sends an email to myself, if the user's manager is blank? For some reason when I run this code, I keep getting line 233 manager email is null.

code is located here: https://stackoverflow.com/a/69731370/18947133

Import-Module ActiveDirectory
$mailprops = @{
from = "test@domainname.com
smtpserver = "server.domain.com"
bodayashtml =$true


}
$startDate = Get-Date
$enddate= $startdate.addDays(x)

$props = @{ filer = "Account expirationDate -gt '$startdate' - and AccountExpiratioDate -lt '$endDate'"

Properties ='Accountexpirationdate', 'Manager' }

$Users = Get-ADuser @props
$bodyScriptBlock = {
# Group all users by their Manager

$Users | Group-Object Manager | ForEach-Object {

# Get this Manager's email address
$managerEmail = (Get-ADUser $_.Name -Properties EmailAddress).EmailAddress

# Create a string[] with the user's Name and their Account's Expiration Date
$userList = foreach($user in $_.Group)
{
    '- {0} expires on {1}' -f $user.Name, $user.AccountExpirationDate
}

# Execute the Body scriptblock passing this user's list
$body = & $bodyScriptBlock -UserList $userList

# Set the remaing values for Mail props
$mailProps.To = $managerEmail
$mailProps.Subject = "Account Expiration Notification for Managees" # ??? No idea what to put here
$mailProps.Body = $body

# Send the email with the list of users
Send-MailMessage @mailProps

Have you tried

if ($null -eq $ManagerEmail)
   {$ManagerEmail = "yourEmail@domain.com"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM