Home > Net >  How to collect all AD users in the loop and put them in the email body?
How to collect all AD users in the loop and put them in the email body?

Time:05-06

Below is what I have:

$DisabledUsers = Get-ADUser -Filter {Enabled -eq $false} -SearchBase 'OU=Users,OU=example,DC=local' 
foreach ($DisabledUser in $DisabledUsers){
    $DisabledUser.Name ';'
    Move-ADObject -Identity $DisabledUser -TargetPath 'OU=Disabled Object,OU=abc,DC=local'
}
write-host $DisabledUser

Send-MailMessage `
                -From 'Disabled Users <[email protected]>' `
                -To 'me <[email protected]>' `
                -Subject 'Disabled User(s) moved to OU=Disabled Object,OU=abc,DC=local' `
                -Body $DisabledUser `
                -SmtpServer "192.168.1.1" `
                -Port "25"
  • write-host $DisabledUser is listing all disabled users
  • However -Body $DisabledUser is showing only 1 user, the last in the loop

Can someone show me the right direction?

CodePudding user response:

Scottwtang's helpful answer shows you where your code uses the wrong variable to put in the Body of the email.

However, outputting $DisabledUser.Name ';' from the loop is not what you intend it to be, because that will only write to the console since you are not capturing that as result.
Then again, why would you, because you already have the array of disabled users in variable $DisabledUsers and all you need from that is a string array with the users names so you can join that into a suitable body text.

Using backticks for cmdlets with a lot of parameters is also something to rethink.
Best use Splatting for that to make the code more robust/readable

Try

$DisabledUsers = Get-ADUser -Filter "Enabled -eq $false" -SearchBase 'OU=Users,OU=abc,DC=local' 
foreach ($user in $DisabledUsers) {
    $user | Move-ADObject -TargetPath 'OU=Disabled Object,OU=abc,DC=local'
}

# Use Splatting for better readability (and get rid of using the nasty backticks)
$mailProps = @{
    From       = 'Disabled Users <[email protected]>'
    To         = 'me <[email protected]>'
    Subject    = 'Disabled User(s) moved to OU=Disabled Object,OU=abc,DC=local'
    Body       = ($DisabledUsers.Name -join [environment]::NewLine)  # join with any character you like
    SmtpServer = '192.168.1.1'
    Port       = 25
}
Send-MailMessage @mailProps

P.S. The -Filter parameter of Get-ADUser is actually a string, not a scriptblock

CodePudding user response:

Based on the code you shared, it seems like

-Body $DisabledUser

should be

-Body $DisabledUsers
  • Related