Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute a PowerShell script automatically using Windows task scheduler?

I have one PowerShell script which sends emails. I want to execute that script automatically, every 1 minute. How can I do it, using task scheduler?

Currently I have created a task and provided the path of my script. But that scheduler opens my script, instead of executing.

I am using Windows 7 Professional and PowerShell version 2.0.5.

like image 857
AK47 Avatar asked May 30 '14 11:05

AK47


3 Answers

Create the scheduled task and set the action to:

Program/Script: Powershell.exe

Arguments: -File "C:\Users\MyUser\Documents\ThisisMyFile.ps1"

like image 159
Kevin_ Avatar answered Oct 17 '22 16:10

Kevin_


Here is an example using PowerShell 3.0 or 4.0 for -RepeatIndefinitely and up:

# Trigger
$middayTrigger = New-JobTrigger -Daily -At "12:40 AM"
$midNightTrigger = New-JobTrigger -Daily -At "12:00 PM"
$atStartupeveryFiveMinutesTrigger = New-JobTrigger -once -At $(get-date) -RepetitionInterval $([timespan]::FromMinutes("1")) -RepeatIndefinitely

# Options
$option1 = New-ScheduledJobOption –StartIfIdle

$scriptPath1 = 'C:\Path and file name 1.PS1'
$scriptPath2 = "C:\Path and file name 2.PS1"

Register-ScheduledJob -Name ResetProdCache -FilePath $scriptPath1 -Trigger  $middayTrigger,$midNightTrigger -ScheduledJobOption $option1
Register-ScheduledJob -Name TestProdPing -FilePath $scriptPath2 -Trigger $atStartupeveryFiveMinutesTrigger
like image 22
JPBlanc Avatar answered Oct 17 '22 15:10

JPBlanc


Instead of only using the path to your script in the task scheduler, you should start PowerShell with your script in the task scheduler, e.g.

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NonInteractive -File "C:\Path\To\Your\PS1File.ps1"

See powershell /? for an explanation of those switches.

If you still get problems you should read this question.

like image 10
Ocaso Protal Avatar answered Oct 17 '22 15:10

Ocaso Protal