Send a csv file with users in AD

How Can We Help?

You are here:
< Back

I got the task to export specific users.

  • All users in a specific OU
  • Send once a month (done by scheduled task)
$date = (Get-Date).ToString("yyyy-MM-dd")
$location = "ADUSERS-" + $date + ".csv"
$recipient = "youremail"
# DONT TOUCH ANYTHING BELOW THIS LINE
"Lets load the AD module"
Import-Module ActiveDirectory
"Get all users and export them to " + $location
Get-ADUser -SearchBase 'OU=YOUROU,DC=company,DC=local' -ResultSetSize 10000 -Filter * -Properties sAMAccountName,displayName,description,office,department,created,AccountExpirationDate,enabled | select-object sAMAccountName,displayName,description,office,department,created,AccountExpirationDate,enabled | Export-CSV -Path $location -Encoding UTF8
"Success in outputting the file, now lets remove all occurences of """
#(Get-Content $location).replace('"', '') | Set-Content $location
"I'm all done and the file is now ready for emailing"

$smtpServer = "yoursmtpserver"
$att = new-object Net.Mail.Attachment($location)
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "fromadress"
$msg.To.Add($recipient)
$msg.Subject = "Users in AD on " + $date
$msg.Body = "Attached is the report

Please open it in Excel and use the 'Text to columns' button on Data tab, split by Comma

Kind regards IT"
$msg.Attachments.Add($att)
$smtp.Send($msg)
$att.Dispose()
"OMG the email has been sent to " + $recipient