Skip to content

Instantly share code, notes, and snippets.

@noahpeltier
Last active September 27, 2023 11:22
Show Gist options
  • Save noahpeltier/a351bd7c82c5aa3b6bb6923522c38e74 to your computer and use it in GitHub Desktop.
Save noahpeltier/a351bd7c82c5aa3b6bb6923522c38e74 to your computer and use it in GitHub Desktop.
Gmail notification with File contents when one is placed in a specified directory
$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path = "C:\temp"
Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Created -Action {
$Object = "{0} was {1} at {2}" -f $Event.SourceEventArgs.FullPath,
$Event.SourceEventArgs.ChangeType,
$Event.TimeGenerated
$Event.SourceEventArgs.FullPath
############################ Get the last file in the directory and pull its contents
$filepath = "C:\temp"
$filename = (get-content $filepath | sort CreationTime -Descending | select -last 1).Name
$Join = Join-Path -path $filepath -ChildPath $filename
$content = Get-Content -Raw $join | out-string
############################ Send the message
$EmailParams = @{
credential = Import-CliXml -Path 'C:\temp\cred.xml' # this needs to be stored prior with "Get-Credential | Export-CliXml -Path C:\path\cred.xml"
From = "email@gmail.com"
To = "email@gmail.com"
Subject = $Object
Body = $content
SMTPServer = "smtp.gmail.com"
Port = "587"
}
Send-MailMessage @EmailParams -UseSsl
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment