如何为一封电子邮件中上传的多个文件发送电子邮件

时间:2016-05-16 22:35:52

标签: powershell powershell-v2.0 powershell-v3.0

我正在使用powershell脚本来监视文件夹中添加的新文件。这个脚本很有效,唯一的问题是它为每个添加的新文件发送一封电子邮件。如果用户要将多个文件拖放到文件夹,我似乎无法为所有添加的文件发送单个电子邮件。例如,如果用户在文件夹中删除3个文件,它应该发送一封包含所有三个文件的链接的电子邮件。这是我第一次使用PowerShell脚本。

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
}
}

此外,我正在尝试将文件设置为电子邮件正文中的链接。我没试过这条线路。

$smtpBody = "[$(Get-Date -Format HH:mm:ss)]`tNew file arrived: <a href='$($FileName)'>$($FileName)</a>"

0 个答案:

没有答案