Export File Names and Their Paths which Contains a Specific Word in Their Filename, Calculate Script Execution Elapsed Time, Send Exported File to Email Recepients

 

#Create a new object to measure the time spend to execute the code
$stopwatch =  [system.diagnostics.stopwatch]::StartNew()
$stopwatch.Start()

#I will append the current date of the code execution to exported files
$CurrentDate = Get-Date
$CurrentDate = $CurrentDate.ToString('dd-MM-yyyy')

#These are the disk drive letters that I wanna scan for the word "crack"
$disks ='D:\', 'E:\', 'F:\', 'G:\', 'H:\', 'I:\', 'J:\', 'K:\', 'L:\'
foreach ($disk in $disks) 
{
$Files="*crack*.*"
Get-ChildItem $disk -Include $Files -Recurse  -ErrorAction SilentlyContinue | select FullName | Export-Csv "C:\filenameScanner_$CurrentDate.csv" -NoTypeInformation -Encoding UTF8 
}

#Exporting the stopwatch elapsed time to a txt file
$duration = "Total Elapsed Time: $($stopwatch.Elapsed.ToString())" 
$duration | Out-File C:\elapsedTime_$CurrentDate.txt
$stopwatch.Stop()



 ######Sending Email########
$fromaddress = “someaddress@yourdomain.com”
$toaddress = “recepient1@yourdomain.com, recepient2@yourdomain.com”
$Subject = “Title”
#create an html file that contains your message
$body = get-content “C:\emailbody.html”
$attachment = “C:\filenameScanner_$CurrentDate.csv”
$smtpserver = “Your SMTP Server”



$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)