Sending an email notification using PowerShell

Kaplan, Andrew H 101 Reputation points
2024-04-02T15:40:37.1866667+00:00

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?

Windows for business Windows Server User experience PowerShell
Windows for business Windows Client for IT Pros User experience Other
{count} votes

3 answers

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2024-04-02T18:50:35.76+00:00

    Replace the Write-Host with Send-MailMessage (and the necessary parameters, of course!).

    1 person found this answer helpful.
    0 comments No comments

  2. 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

  3. Anonymous
    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.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.