Here’s a PowerShell script that exports a list of users from Active Directory, creates a CSV file, and sends it as an attachment with an HTML email body:
# Define variables
$smtpServer = "your_smtp_server"
$from = "sender@example.com"
$to = "recipient@example.com"
$subject = "Active Directory Users Report"
$htmlBody = @"
<html>
<head>
<title>Active Directory Users Report</title>
</head>
<body>
<p>Below is the list of users from Active Directory:</p>
</body>
</html>
"@
# Error handling function
function Handle-Error {
param([string]$errorMessage)
Write-Host "Error: $errorMessage" -ForegroundColor Red
exit 1
}
# Export users from Active Directory to CSV
try {
Get-ADUser -Filter * -Properties * | Select-Object Name, SamAccountName, Email |
Export-Csv -Path "AD_Users_Report.csv" -NoTypeInformation -Force
} catch {
Handle-Error "Failed to export users from Active Directory"
}
# Send email with CSV attachment and HTML body
try {
$attachment = "AD_Users_Report.csv"
Send-MailMessage -SmtpServer $smtpServer -From $from -To $to -Subject $subject -BodyAsHtml $htmlBody -Attachment $attachment
} catch {
Handle-Error "Failed to send email with CSV attachment"
}
# Clean up CSV file
try {
Remove-Item "AD_Users_Report.csv" -ErrorAction SilentlyContinue
} catch {
Handle-Error "Failed to delete temporary CSV file"
}
For this script to work, it needs to be executed on a machine that is joined to the Active Directory domain or has access to the Active Directory environment. This is because the Get-ADUser cmdlet, which retrieves user information from Active Directory, requires access to an Active Directory domain controller.
Script explanation:
- Variables:
$smtpServer: SMTP server address for sending emails.$from: Sender’s email address.$to: Recipient’s email address.$subject: Subject of the email.$htmlBody: HTML content of the email body.
- Error Handling Function (
Handle-Error):- This function takes an error message as input and displays it in red color. It then exits the script with exit code 1.
- Export Users from Active Directory:
- Uses
Get-ADUsercmdlet to retrieve all users from Active Directory. - Selects specific properties (Name, SamAccountName, Email).
- Exports the result to a CSV file using
Export-Csv.
- Uses
- Sending Email:
- Uses
Send-MailMessagecmdlet to send an email. $smtpServer,$from,$to,$subject,$htmlBody, and$attachmentare used to compose the email.-BodyAsHtmlparameter is used to specify that the body of the email is in HTML format.
- Uses
- Clean Up:
- Removes the temporary CSV file after sending the email. This ensures that no unnecessary files are left behind.
Recommended Reading: Active Directory Administration with PowerShell – pt. 1
