Powershell电子邮件通知文件已创建

时间:2018-08-14 13:36:14

标签: powershell email temp

我已经为PowerShell编写了一个代码,以便在将新文件添加到指定文件夹时通知我,但是每次打开该文件时,它都会创建一个临时文件,每次打开该文件时,我都会不断收到这些电子邮件。我试图创建一个if-else语句,以便临时文件电子邮件转到其他电子邮件地址。理想情况下,我完全不希望收到这些电子邮件。如果您知道有可能的方法,请帮助我。我已经在下面复制了我的代码。

$folder = "File Folder Path"
$mailserver = "mailserver"
$recipient = "Recipient@Email.com"

$fsw = New-Object System.IO.FileSystemWatcher $folder -Property @{
   IncludeSubdirectories = $true
   EnableRaisingEvents=$true
}


$created = Register-ObjectEvent -InputObject $fsw -EventName Created -SourceIdentifier CreatedEvent -Action {
   $item = Get-Item $eventArgs.FullPath
   $s = New-Object System.Security.SecureString
   $anon = New-Object System.Management.Automation.PSCredential ("NT AUTHORITY\ANONYMOUS LOGON", $s)
   If ($fsw -ccontains '~') {
      Send-MailMessage -To "MyEmail@Email.com" `
                    -From "Email@Email.com" `
                    -Subject “File Creation Event” `
                    -Body "A file was created: $($eventArgs.FullPath)" `
                    -SmtpServer $mailserver `
                    -Credential $anon
    }
   Else {
      Send-MailMessage -To $recipient `
                    -From "Email@Email.com" `
                    -Subject “File Creation Event” `
                    -Body "A file was created: $($eventArgs.FullPath)" `
                    -SmtpServer $mailserver `
                    -Credential $anon
    }
}

1 个答案:

答案 0 :(得分:3)

包含对数组而不是字符串的工作。使用-like-match

如果您不希望发送电子邮件,请不要编写发送电子邮件的代码。

例如,仅当您的临时文件不包含~时,此命令才发送电子邮件。除此之外,如果文件名确实包含~,则不会采取任何措施。

If ($fsw -notlike '*~*') {
  Send-MailMessage -To $recipient `
                -From "Email@Email.com" `
                -Subject “File Creation Event” `
                -Body "A file was created: $($eventArgs.FullPath)" `
                -SmtpServer $mailserver `
                -Credential $anon
}