Create Scheduled Task or Scheduled Job to Indefinitely Run a PowerShell Script Every 5 Minutes

Here are two straight-forward ways to create Scheduled Tasks within Windows using PowerShell. One script creates a PowerShell Scheduled Job, and the other creates a classic Windows Scheduled Task. You can read about the differences here. PowerShell v3 and above required.

Create a Scheduled Job

The following script creates a PowerShell Scheduled Job which shows up in the Task Scheduler GUI, and also generates files located at:

$home\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs\\Output

I included the options that I most often use — repeat every X indefinitely, run as specified user, and run with highest privileges. Note that you should always use service accounts or accounts without expiring or changing passwords when setting up Scheduled Jobs and Scheduled Tasks.

This job will appear under Task Scheduler -> Task Scheduler Library -> Microsoft -> Windows -> PowerShell -> ScheduledJobs.

taskscheduler

These Scheduled Jobs can be managed within PowerShell using cmdlets.

Create a Scheduled Task

This script will generate a new Scheduled Task. As previously stated, I included the options that I most often use — repeat every X indefinitely, run as specified user, and run with highest privileges. Note that you should always use service accounts or accounts without expiring or changing passwords when setting up Scheduled Jobs and Scheduled Tasks.

taskscheduler2
This job will appear under Task Scheduler -> Task Scheduler Library. Also, don’t forget to return $true or $false. If you don’t, the “Last Run Result” will be 0x1.

Chrissy is a PowerShell MVP who has worked in IT for nearly 20 years, and currently serves as a Sr. Database Engineer in Belgium. Always an avid scripter, she attended the Monad session at Microsoft’s Professional Developers Conference in Los Angeles back in 2005 and has worked and played with PowerShell ever since. Chrissy is currently pursuing an MS in Systems Engineering at Regis University and helps maintain RealCajunRecipes.com in her spare time. She holds a number of certifications, including those relating to SQL Server, SuSE Linux, SharePoint and network security. She recently became co-lead of the SQL PASS PowerShell Virtual Chapter. You can follow her on Twitter at @cl.

Posted in PowerShell, Windows
10 comments on “Create Scheduled Task or Scheduled Job to Indefinitely Run a PowerShell Script Every 5 Minutes
  1. Michael McNally says:

    “always use service accounts” is a good suggestion, and works well enough for the account running the task. However, the Powershell Job is still stored under $home of the person creating the task. This could potentially cause issues in business environment if the person that created the task leaves. Short of doing something sneaky like using a scheduled task to create the scheduled task, I can’t think of a good way around this problem

    • Chrissy LeMaire says:

      >> However, the Powershell Job is still stored under $home of the person creating the task.

      Wow, I didn’t put that together. A better way of doing it, then, would probably be to run PowerShell under the service account credentials then create the task that way.

  2. Miodrag Milić says:

    Your task will stop after 3 days. Use:

    $s = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (Time-Span…)

    Since its not possible AFAIK to disable this option you need to specify some large value to run non-stop, such as 9999 days.

  3. gautam says:

    Hi chrissy

    I ama trying to create a scheduled task that run every 15 minutes everyday at 3 am in morning and stops at 12 am midnight means it run for 21 hrs and every 15 minutes.When I try to edit the your script it is not working properly.Need any helpful reply in that

    $jobname = “Recurring PowerShell Task”
    $script = “C:\BatchFile.bat”
    $repeat = (New-TimeSpan -Minutes 5)

    # The script below will run as the specified user (you will be prompted for credentials)
    # and is set to be elevated to use the highest privileges.
    # In addition, the task will run every 5 minutes or however long specified in $repeat.
    $scriptblock = [scriptblock]::Create($script)
    $trigger = New-JobTrigger -Daily -At “3 AM” -RepeatIndefinitely -RepetitionInterval $repeat
    #$msg = “Enter the username and password that will run the task”;
    #$credential = $Host.UI.PromptForCredential(“Task username and password”,$msg,”$env:userdomain\$env:username”,$env:userdomain)

    $options = New-ScheduledJobOption -RunElevated -ContinueIfGoingOnBattery -StartIfOnBattery
    Register-ScheduledJob -Name $jobname -ScriptBlock $scriptblock -Trigger $trigger -ScheduledJobOption $options

  4. Mark Bulmer says:

    Wow! Super-demo. Thanks Chrissy. It helped me get started in running a script to get VMs to export every week.

  5. argha guha biswas says:

    geting below error while trying to schedule any help please? I am running the script in windows server 2012 r2′
    The task XML contains a value which is incorrectly formatted or out of range.
    (10,42):Duration:P99999999DT23H59M59S
    At C:\PowershellScripts\ScheduledJob.ps1:19 char:1
    + Register-ScheduledTask -TaskName $jobname -Action $action -Trigger $t …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (PS_ScheduledTask:Root/Microsoft/…S_ScheduledTask) [Register-ScheduledTa
    sk], CimException
    + FullyQualifiedErrorId : HRESULT 0x80041318,Register-ScheduledTask

  6. Daniel says:

    Hi there,
    please, could you help me with trigger for my scheduled job? I’ve got a problem. When I set JobTrigger ($trigger = New-JobTrigger -Daily -At 2:00), so my scheduled job for runs only once. Another day nothing happens. But when I set a new trigger, again with parametr -Daily, so it runs only once again. My scheduled job is for run a script. So, I’d like ask you for help, because I want to run this script every day at the same time without setting a new trigger again and a again. Do you have any ideas?
    Thank you, Daniel.
    PS: Sorry for my english, I’m not for english speaking country :D

  7. Nice post !
    Exactly what I was looking for.
    Thanks :-)

  8. raj says:

    Hi I am looking for ps script to uncheck stop task if it runs longer than 3 days triggers …..please help

    • Chrissy LeMaire says:

      I just figured it out. it only works on Scheduled Tasks and you gotta use

      $settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([timespan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable -DontStopOnIdleEnd

      the ExecutionTimeLImit is important.

Leave a Reply

Your email address will not be published. Required fields are marked *

*