Exchange Online
A Microsoft email and calendaring hosted service.
6,171 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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
}
}