Search code examples
powershellemailnotificationssmtpdirectory

PowerShell: Check a folder for changes and if so, send an e-mail


I have a colleague with loads of creative ideas, but I've got no talent with PowerShell. He wants a folder to be checked regularly for changes. As soon as a new file has been added to the folder, he wants to be notified via mail. So, I guess I need a PS script for that.

I have absolutely no idea on how to do this, though.

I found the following code - can this be altered to do the job?

Param (
    [string]$Path = "C:\Test",
    [string]$SMTPServer = "SMTP IP",
    [string]$From = "[email protected]",
    [string]$To = "[email protected]",
    [string]$Subject = "New stuff!"
)

$SMTPMessage = @{
    To         = $To
    From       = $From
    Subject    = "$Subject at $Path"
    Smtpserver = $SMTPServer
}

$File = Get-ChildItem $Path | Where { $_.LastWriteTime -ge [datetime]::Now.AddMinutes(-1) }
If ($File) {
    $SMTPBody = "`nThe following files have recently been added/changed:`n`n"
    $File | ForEach { $SMTPBody += "$($_.FullName)`n" }
    Send-MailMessage @SMTPMessage -Body $SMTPBody
}

Any help would be appreciated.


Solution

  • To get notified about changes on a particular folder, and/or its sub items, one can use .Net Frameworks FileSystemWatcher class. Instantiate a new one with PowerShell using:

    $pattern = "*.*"
    $watcherProperties = @{
        IncludeSubdirectories = $false;
        NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
        }
    $watcher = New-Object IO.FileSystemWatcher $Path, $pattern -Property @watcherProperties
    

    Then, to get notified about changes, register an event using Register-ObjectEvent and add your mail block:

    Register-ObjectEvent $watcher Created -SourceIdentifier FileCreated -Action {
        $SMTPBody = "`nThe following file have recently been added/changed:`n`n$($Event.SourceEventArgs.Name)"
        Send-MailMessage @SMTPMessage -Body $SMTPBody}
    }
    

    While this is a nice solution to get automatically notified, without heavy loops, it also has some drawbacks. In this configuration you would get one mail for every file changed. Moving directories with bunches of files would result in - bunches of mails.

    You can read more about FileSystemWatchers here: