Wednesday, November 15, 2023

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

Create schedule task using PowerShell

 

$Action = New-ScheduledTaskAction "powershell.exe "D:\ADScripts\Get-ADusers-RITM-Monthly-Report.ps1""

$Trigger = New-ScheduledTaskTrigger -Weekly -WeeksInterval 2 -DaysOfWeek Sunday -At 3am

$Principal = New-ScheduledTaskPrincipal -UserID AD-HMR$ -LogonType Password

$taskname = "AD Enabled Users List Monthly Report"

$Taskpath = "AD-Tasks"

$TaskDescription = "AD Enabled users List, This task will generate the Enabled users list and send it to Bix and bbntech as Attachment file."

Register-ScheduledTask  –Action $Action –Trigger $Trigger –Principal $Principal -TaskName $taskname -Description $TaskDescription -taskPath $Taskpath 

#$Time = New-ScheduledTaskTrigger -Monthly -WeeksInterval 4 -DaysOfWeek Monday -At 3am

#Set-ScheduledTask -TaskName "Arcosa Enabled Users List Monthly Report" –Principal $Principal -taskPath $Taskpath