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 “& ‘SomeDirmyScript.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

4 thoughts on “Send email with Powershell script, schedule script with Windows Task Scheduler”

  1. 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 “& ‘SomeDirmyScript.ps1′”
    oProcess.Start()
    oProcess.WaitForExit(1000 * iTimeOutSec)

    Like

  2. trying to send an email using powershell. I have a working code but when I substitute “From” and “To” to variables like “From=$source
    “To=$destination
    I get an error

    working code is

    $messageParameters = @{
    smtpServer = “smtphost”
    From = md@yahoo.com
    To = md@yahoo.com
    Subject = “You Submitted a Job”
    Body = “Your Job Chain is submitted successfully”
    }
    Thanks for help 🙂

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: