Email notification and enable logging

Hi

I have the below script which basically zip, moves and delete logs files on a monthly basis, some users from this forums has helped me previously on adjusting a few lines, and that has worked as expected. Now, I would like to add futher functionality to the script.

#get the list of files in the original folder
$rootFolder = “C:\Windows\System32\LogFiles\W3SVC1”
$archivefolder = “E:\Logs\Intranet\Archive Logs\2018”
$tempVariable = $rootFolder
$files = Get-ChildItem -Path $rootFolder | Where-Object {$_.Name -like ‘*.log’}

#create a temporary folder using today’s date
$tempFolderRoot = “C:\Temp_”
$date = (((Get-Date).AddMonths(-0)).AddDays(-$(Get-Date).Day)).ToString(“yyMM01-dd”)
$tempFinalFolder = “$tempFolderRoot$date”
New-Item -ItemType directory -Path $tempFinalFolder -Force

#decide how long back to go
$timespan = new-timespan -days 0

#move the files to a temporary location
foreach($file in $files)
{
$fileLastModifieddate = $file.LastWriteTime
if(((Get-Date) - $fileLastModifiedDate) -gt $timespan)
{
Move-Item “$rootFolder$file” -destination $tempFinalFolder
}
}

$CompressionToUse = [System.IO.Compression.CompressionLevel]::Optimal
$IncludeBaseFolder = $false
$zipTo = “{0}\ex{1}.zip” -f $archivefolder,$date

#add the files in the temporary location to a zip folder
[Reflection.Assembly]::LoadWithPartialName( “System.IO.Compression.FileSystem” )
[System.IO.Compression.ZipFile]::CreateFromDirectory($tempFinalFolder, $ZipTo, $CompressionToUse, $IncludeBaseFolder)

#Remove-Item $tempFinalFolder -RECURSE

I wonder if anyone can help me or show me how to add the below functionality to the script:

  1. Email notification: Once the script has completed running an email need to be sent to a mailbox.
  2. Enable Logging: Once the script has completed running a log file to be generated confirming that script successful or failed.

Many thanks in advance.

You could do yourself and us a favor and format your code as code. And even better would be when you indent your code accordingly. It makes it easier to read and to understand and to debug and … :wink:
If you like to send an email you can use the cmdlet Send-MailMessage. To output something to a file you could use as a really simple solution the cmdlet Out-File. Of course there are as always more sophisticated approaches thinkable. You could search the Powershell gallery for “logging”.

Thanks for your feedback Olaf.