Send an e-mail message from PowerShell.

This small PowerShell script will send you an e-mail message to notify you about something. I used it as a monitor for a custom, non-Microsoft service running on Windows Server 2008. Whenever the service will stop for an unexpected reason, the support guys will quickly be notified about the failure. The PowerShell script looks like this:

$EmailFrom = “<e-mail address>@<>”
$EmailTo = “<e-mail address>@<>”
$Subject = “<Enter your subject here>”
$Body = “<Enter the body message here>”
$SmtpServer = “<Enter the FQDN of your SMTP server>”
$smtp = New-Object net.mail.smtpclient($SmtpServer)
$smtp.Send($EmailFrom, $EmailTo, $Subject, $Body)

According to Microsoft Scripting Guys, as a security measure, you can’t start a PowerShell script by double-clicking a .PS1 file. So if you want to run this script from a scheduled task or when a service failure occurs you can create a VBS script that calls the PowerShell script:

Set objShell = CreateObject(“WScript.Shell”)
objShell.Run(“powershell.exe c:scripts<script name.ps1>”)

You can copy and paste the code above to create the .PS1 and .VBS script files or you can download the PowerShell script here and the VBS Script here. Change the extension of the files .PS1 and .VBS accordingly.

One last thing; don’t forget to add the Windows PowerShell feature and to set the right PowerShell execution policy on your Windows Server 2008 system :-).


– Marek.Z

Be the first to comment

Leave a reply...