Send email with Powershell script, schedule script with Windows Task Scheduler

Here is a set of samples I used to do a common task in my scripting life.  This go around I wanted to use Powershell. 

 

A) Create a script to send emails in powershell
----------------------------------------------------
1) Open Powershell type set-executionpolicy Unrestricted 
'This allows scripts to be run'
'You'll want to also look at using RemoteSigned
Type

2) Type Notepad myscript.ps1


3) Paste sample code and save in myscript.ps1


$SmtpClient = new-object system.net.mail.smtpClient
$SmtpServer = "localhost"
$SmtpClient.host =
$SmtpServer
 

$From = "Friendly Reminder <User@example.com>"
$To = User2@example.com
$Title = "Subject Matter"
$Body = "Body Text" 
$SmtpClient.Send($from,$to,$title,$Body)  

B) Testing Script
----------------------------------------------------
1) Type ./myscript.ps1
'Verify you receive the email.  

C) How to schedule a powershell script in Windows Task Scheduler
----------------------------------------------------
1) Create a new scheduled task.

'The syntax is to execute the script is:
powershell -command "& 'SomeDir\myScript.ps1'" 

2) Set the script to run as your normal task scheduler accounts.

 

3) Execute task, verify you receive the email

Hope this helps,

Steve

Published Wednesday, January 09, 2008 10:27 AM by steve schofield
Filed under:

Comments

# Send email with Powershell script, schedule script with Windows Task Scheduler - Steve Schofield Weblog

Pingback from  Send email with Powershell script, schedule script with Windows Task Scheduler - Steve Schofield Weblog

# re: Send email with Powershell script, schedule script with Windows Task Scheduler

Thursday, January 10, 2008 5:28 PM by Neel

I am trying to use the same command in process can you please help me out here

Dim oProcess As Process = New Process

oProcess.StartInfo.UseShellExecute = False

oProcess.StartInfo.RedirectStandardOutput = True

oProcess.StartInfo.CreateNoWindow = False

oProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal

oProcess.StartInfo.FileName = "powershell.exe"

Dim sArguments as string = powershell -command "& 'SomeDir\myScript.ps1'"

oProcess.Start()

oProcess.WaitForExit(1000 * iTimeOutSec)

# re: Send email with Powershell script, schedule script with Windows Task Scheduler

Thursday, January 10, 2008 11:00 PM by steve schofield

Are you trying to do this in a console application?