I am using a powershell script that monitors a folder for new files added. This script works great the only problem is that it sends an email for every new file added. I can't seem how to get it to send a single email for all files added if a user was to drag and drop multiple files to folder. For instance if a user drops 3 files in the folder it should send one email with the links to all three files. This is my first time using powershell scripts.
PowerShell.exe -windowstyle hidden{
$MonitorFolder = "C:\Users\RickG\Desktop\Test Reports"
$MonitorStopFile = "monitor.die"
$smtpServer = "mail.rtg.org"
$smtpFrom = "SYSTEMFUNCTION@rtg.org"
$smtpTo = "rickg@rtg.org"
$smtpSubject = "New file arrived in $($MonitorFolder)."
$SourceID = "MonitorFiles"
$Query = @"
SELECT * FROM __InstanceCreationEvent WITHIN 10
WHERE targetInstance ISA 'Cim_DirectoryContainsFile'
AND targetInstance.GroupComponent = 'Win32_Directory.Name="$($MonitorFolder.Replace("\", "\\\\"))"'
"@
Try {
$smtp = New-Object -TypeName "Net.Mail.SmtpClient" -ArgumentList $smtpServer
Register-WmiEvent -Query $Query -SourceIdentifier $SourceID
Do {
"Waiting for a new file to arrive in '$($MonitorFolder)'; to stop, hit <Ctrl-C> or create a file '$MonitorStopFile'." | Write-Host
$FileEvent = Wait-Event -SourceIdentifier $SourceID
Remove-Event -EventIdentifier $FileEvent.EventIdentifier
$FileName = $FileEvent.SourceEventArgs.NewEvent.TargetInstance.PartComponent.Split("=", 2)[1].Trim('"').Replace("\\", "\")
If ((Split-Path -Path $FileName -Leaf) -eq $MonitorStopFile) {
$smtpBody = "[$(Get-Date -Format HH:mm:ss)]`tStop file arrived: '$($FileName)'; monitor is going down!"
Remove-Item -Path (Join-Path -Path $MonitorFolder -ChildPath $MonitorStopFile)
$FileEvent = $Null
} Else {
$smtpBody = "[$(Get-Date -Format HH:mm:ss)]`tNew file arrived: $($FileName)"
}
$smtpBody | Write-Host -Fore Yellow
$smtp.Send($smtpFrom, $smtpTo, $smtpSubject, $smtpBody)
} While ($FileEvent)
} Catch {
$_ | Out-String | Write-Error
} Finally {
Remove-Event -SourceIdentifier $SourceID -ErrorAction SilentlyContinue
Unregister-Event -SourceIdentifier $SourceID -ErrorAction SilentlyContinue
}
}
Also I am trying to make the file a link in the body of the email. I have tried this line with no luck.
$smtpBody = "[$(Get-Date -Format HH:mm:ss)]`tNew file arrived: <a href='$($FileName)'>$($FileName)</a>"