Create a Monthly report using schedule task using PowerShell script
#Would talk about pre-requisites for importing ActiveDirectory Module at end of post
import-module ActiveDirectory
#Preparing files to write data and attach to email
$file1 = "D:\Bixam\AD_Enabled_Users\Arcosa_Enabled_Users_list_$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv"
Get-ADUser -filter "enabled -eq'true'" -Properties * | Select-object @{N="AD Emplid"; E={$_.employeeid}},@{N="AD Emplnum"; E={$_.employeenumber}},@{N="Employee Name"; E={$_.displayNameprintable}},@{N="Segment"; E={$_.extensionattribute6}},@{N="Company"; E={$_.extensionattribute2+"-"+$_.extensionattribute3}},@{N="Business Unit"; E={$_.company}},@{N="EE Type"; E={$_.employeetype}},@{N="Country"; E={$_.co}},@{N="Email Address"; E={$_.mail}},@{N="AD Network ID"; E={$_.samaccountName}} | export-csv "$file1" -NoTypeInformation
#Email related settings
$smtpServer = "smtp.bbntech.com"
$att1 = new-object Net.Mail.Attachment($file1)
##$att2 = new-object Net.Mail.Attachment($file2)
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "AD-Reports@bbntech.com"
$msg.To.Add("email1@bbntech.com")
$msg.To.Add("email2@bbntech.com")
$msg.To.Add("email3@bbntech.com")
$msg.Subject = "List of AD Enabled Users report"
$msg.Body = "Attached is the List of Arcosa Enabled Users report, its Monthly report scheduled to send email with an attachment"
$msg.Attachments.Add($att1)
##$msg.Attachments.Add($att2)
$smtp.Send($msg)
$att1.Dispose()
##$att2.Dispose()
#### Keeps only 24 files and removes older files###
$path = "D:\Folder\AD_Enabled_Users"
$files = Get-ChildItem -Path $path -Recurse | Where-Object {-not $_.PsIsContainer}
$keep = 24
if ($files.Count -gt $keep) {
$files | Sort-Object CreationTime | Select-Object -First ($files.Count - $keep) | Remove-Item -Force
}
#Script ends here
Comments