Automate Emailing of Latest Excel Reports from Shared Folders Using PowerShell

Automatically send the latest Excel file from a shared folder via email, along with the file's creation date, using a simple PowerShell script. No more manual checks

# Configuration
$sharedFolder = "\\YourSharedServer\SharedFolderPath"
$smtpServer = "smtp.yourdomain.com"
$from = "sender@yourdomain.com"
$to = "recipient@yourdomain.com"
$subject = "Latest Excel File from Shared Location"

# Get the latest Excel file
$latestFile = Get-ChildItem -Path $sharedFolder -Filter *.xls* |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 1

if ($latestFile) {
    $filePath = $latestFile.FullName
    $fileName = $latestFile.Name
    $fileDate = $latestFile.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")

    $body = @"
Hello,

Please find the latest Excel file attached.

**File Name:** $fileName  
**Generated On:** $fileDate

Regards,  
Your DBA Automation
"@

    # Send email with attachment
    Send-MailMessage -From $from -To $to -Subject $subject -Body $body `
        -SmtpServer $smtpServer -BodyAsHtml -Attachments $filePath
} else {
    Write-Host "No Excel file found in the shared folder."
}

No comments:

Post a Comment