Replace the Write-Host with Send-MailMessage (and the necessary parameters, of course!).
Sending an email notification using PowerShell
Hello.
I am running Windows Server 2019, and I am running the PowerShell script shown later in this posting. The particulars for Powershell are the following:
Major Minor Build Revision
5 1 17763 4974
The script that I am running is designed to notify me of changes to files within a particular directory. The code is shown below:
$folder = '\\localhost\c$\Output\Connection'
$filter = '*.*'
$destination = '\\localhost\c$\tmp'
$fsw = New-Object IO.FileSystemWatcher
$fsw.Path = $folder
$fsw.Filter = $filter
$fsw.IncludeSubdirectories = $true
$fsw.EnableRaisingEvents = $true
$fsw.NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
$action = {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp"
Copy-Item $path -Destination $destination -Force -Verbose
}
$created = Register-ObjectEvent $fsw Created -Action $action
while ($true) {sleep 1}
Currently the script displays the change notifications on-screen. I want to have the script send me email notifications as well. What command(s) can I add to the script to accomplish this?
3 answers
Sort by: Most helpful
-
-
Deleted
This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.
Comments have been turned off. Learn more
-
Ian Xue 36,751 Reputation points Microsoft Vendor
2024-04-03T05:30:49.6333333+00:00 Hi Kaplan, Andrew H,
Please refer to the examples in this document.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage
Best Regards,
Ian Xue
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.