Powershell check file modified date & send email if updated (only once)

Pavel Kuznetsov 0 Reputation points
2023-02-10T20:02:26.3733333+00:00

Script sends email if a new file is found in that folder.

And does not send email if already been sent.

Runs every hour in the windows task scheduler.

Can you check the code? Maybe you can tell me how to fix it and optimize it. Thank you.

$TodayDate = Get-Date -f dd-MM-yyyy
$folderpath = "C:\Users\My\Downloads\"
$filename = "log-$TodayDate.log"
$LogFile = "C:\Users\My\Downloads\log-$TodayDate.log"

if (!(Test-Path $LogFile)) {
    New-Item -itemType File -Path $folderpath -Name $filename

    if ((get-item $LogFile).Length -gt 0) {
        $Line = Get-Content -Path $LogFile | Select-Object -last 1
        $Date = $Line.replace("File Processed on ", "")
    } else {
        $Date = $null
    }

    function WriteLog {
        Param([string] $LogString)
        $Stamp = ($WatchDogFile.LastWriteTime).ToString("dd.MM.yyyy HH:mm:ss")
        $LogMessage = "$LogString $Stamp"
        Add-content $LogFile -value $LogMessage
    }

    $Files = Get-ChildItem -Path "D:\la\la"

    $WatchDogFile = $Files | Sort-Object -Property LastWriteTime -Descending | Select-Object -First 1
    $TodayDate = Get-Date

    if (($Date -eq $null) -or($Date -lt($WatchDogFile.LastWriteTime).ToString("dd.MM.yyyy HH:mm:ss"))) {

        #if
        #($WatchDogFile.LastWriteTime.Date -eq $TodayDate.Date)

        $MailMessage = @{
            To = "my@example.com"
            From = "my@example.com"
            Subject = "New file"
            Body = "<h2>File</h2> <p><strong>Updated:</strong> $($WatchDogFile.LastWriteTime.ToString("dd.MM.yyyy hh:mm"))</p>"
            Smtpserver = "smtp.example.com"
            BodyAsHtml = $true
            Encoding = "UTF8"
            Attachment = $WatchDogFile.FullName
        }
        Send-MailMessage @MailMessage

        WriteLog "File Processed on"

    } else {
        exit
    }
}
Exchange Online
Exchange Online
A Microsoft email and calendaring hosted service.
6,171 questions
Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.