Get-ADUser and send-MailMessage

Hi,

Just getting in PowerShell and seeing if it’s possible to combine Get-ADUser and send-MailMessage commands? What i’m trying to do is find any enabled accounts in an OU then email out the list. I’ve seen examples of putting the results into a file first then sending the email but would’ve thought it can be done form the Get-ADUser output.

I can run the AD lookup script and send-MailMessage separately but can’t seem to get it working within one script.

Thanks.

send-mailmessage doesn’t take pipeline input for the -to option, so you’ll have to pipe to a foreach-object loop. Something like:

get-aduser joe -property emailaddress | 
foreach-object { send-mailmessage -to $_.emailaddress } 

I believe what you’re asking:

 

  1. Find enabled accounts in an OU
  2. Pipe that in an email and then send
You're not looking to send an email to the enabled accounts.
$MailParams = @{
To = @("me@my.com")
From = "me@my.com"
SmtpServer = "mailrelay.my.com"
}

$mailParams.body = get-aduser |out-string

Send-MailMessage @MailParams

Hi,

Sorry, i don’t think i was clear. I don’t want to send an email to any user who’s account is enabled, but to a shared mailbox so we can audit the accounts.

So i would run this command:

Get-ADUser -Filter * -SearchBase "OU=,OU=,DC=,DC=" -Property Enabled, DisplayName, EmailAddress, Description, Office | Where-Object {$_.Enabled -like “true”} | select Enabled, DisplayName, EmailAddress, Description, Office

Then want the results to be emailed to one address.

Thanks.

That seems to be the code i need - thank you.

It should work, the issue being body needs to be a string and not an object (I had to go back and redo my initial answer). However, I would think export-csv and then attaching it would make the list more manageable if you have a lot of accounts to sift through

There’s only a handful of accounts in the OU to audit, and it emails in a readable format now thanks.

I also needed to add in the ‘Subject’ parameter as PowerShell seemed to be prompting me for this before sending.

$MailParams = @{
To = @("me@my.com")
From = "me@my.com"
SmtpServer = "mailrelay.my.com"
Subject = "something"
}

Yeah, I let that out. I tend to do something like “subject = Blah from $env:computername” So I know what server generates the email, in case years later there’s a question on how its being generated.