次の方法で共有


Configuring Advanced Scheduled Task Parameters Using PowerShell

Scenario

I recently was working with a script that had very specific requirements:

  1. The script had to run as a scheduled task
  2. The scheduled task itself had to be created using PowerShell
  3. The script had to run once the servers started up
  4. The task had to repeat every 10 minutes for 1 day

Creating a scheduled task is pretty straight forward and is well documented here. But I quickly discovered that creating a scheduled task with the specific parameters that were needed is not as simple as it might seem. In this blog post I am going to show you how to create a scheduled task using Powershell, call a PowerShell script using that scheduled task, and configure parameters of the scheduled task that are not provided through the PowerShell Scheduled Task cmdlets. So lets go ahead and create an example scheduled task that meets all of the requirements.

Create a Sample Script

First lets create a very basic sample script that the scheduled task will run. The following code simply records the date and time and outputs it to a log file in the same folder as the script.

#Stores Script's Current Location
$sCurrDir = $myinvocation.mycommand.path
$sCurrDir = $sCurrDir.Replace("\" + $myinvocation.MyCommand, "")

#Log Output Path
$OutputPath = "$sCurrDir\SampleScheduledTask.log"

#Outputs to log file
function Write-Log{
param(
    [string]$OutputPath
)

    #Stores Date / Time
    $Date = $TimeStamp = (get-date).toshortdatestring(); $Time = (get-date).tolongtimestring()

    #Creates Output Message
    $Message = "I ran on $Date at $Time"

    #Writes Output Message to log file
    $Message | Add-Content $OutputPath
}
#Calls Log Function
Write-Log -OutputPath $OutputPath

Some astute readers may question why I created a function for such a simple script. The answer is because I like to provide complete examples that will provide you not just the answer to your original questions but also illustrate good coding practices and clarifying concepts that will help you write a more complete script. In this post I am not only going to show you how to automate the creation of a scheduled task and how to modify its advanced parameters, I am also going to create the scheduled task and run an example script all using the same script.

Saving The Script

Now that we have the start of the sample script it is important to save it in the following location for the purposes of this example:

           C:\SampleScheduledTaskScript

Create a folder with that path and save the script in the folder with the name:

          SampleScheduledTaskScript.ps1

So the full path to the script should be:

       C:\SampleScheduledTaskScript\SampleScheduledTaskScript.ps1

It is important that this structure and naming convention be followed for the purposes of this example.

Creating The Scheduled Task

At this point we have our sample script, now we just need it to run as a scheduled task.  So lets create the scheduled task:

We want the script to run regardless of the current execution policy, so we create the following task action:

#Creates Scheduled Task Action
$TaskAction1 = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument "-ExecutionPolicy Bypass -File ""C:\SampleScheduledTaskScript\SampleScheduledTaskScript.ps1""

Next we want the scheduled task to run as system so we create the following Task Principal:

#Assigns Task Principal
$TaskUserName = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest

The scheduled task must run at startup so we create the following entry:

#Task Trigger
$TaskTrigger  = New-ScheduledTaskTrigger -AtStartup

Next we create the scheduled task:

#Create Scheduled Task
$Task = New-ScheduledTask -Action $TaskAction1 -Principal $TaskUserName -Trigger $TaskTrigger -Settings $TaskSettings 

And lastly we register the scheduled task

#Register Scheduled Task
Register-ScheduledTask SampleScheduledTask -InputObject $Task -Force

The Missing Parameters

Great, so now we have a script, a scheduled task that runs the script, and it will run every time the server or workstation is started up. But we have failed to meet one of the requirements; the task must also repeat every 10 minutes for 1 day. If you go back and attempt to add a repetition interval or repetition duration you will notice that neither are an option for the -AtStartup parameter:

Through the GUI the scheduled task parameters are available:

But they are not available via the PowerShell New-ScheduledTaskTrigger cmdlet if you choose the -AtStartup parameter. They are available via the -Once parameter but that would not meet the requirements. The solution is to directly modify the task's properties using its XML schema. This may sound complicated at first but in reality it is very easy and will allow you to modify practically every parameter of the scheduled task.

Step 1  - Get the scheduled task. The first step is to get the scheduled task that you just created and store it in an object.

$Task = Get-ScheduledTask -TaskName "SampleScheduledTask"

Step 2 - Update the specific property of the task that you wish to modify. For this example we wish to add a repetition duration and a repetition interval.

$Task.Triggers.Repetition.Duration = "P1D"
$Task.Triggers.Repetition.Interval = "PT10M"

You are probably wondering how I knew P1D would equal a duration of 1 Day and how I knew PT10M would equal a repetition interval of 10 minutes since neither are the typical date/time or timespan values that you are probably used to working with. To get those values I simply configured the duration and interval that I wanted through the GUI then viewed the result through Powershell  using the following command: $Task.Triggers.Repetition | fl *

Step 3 - Save the new configuration to the scheduled task. Remember, you must re-enter the credentials for the task here or the operation will fail.

$Task | Set-ScheduledTask -User "NT AUTHORITY\SYSTEM"

Validation

The scheduled task should now meet all of the requirements; lets validate that it does indeed run at startup and repeat every 10 minutes for a day. You can either validate through PowerShell or through the GUI, lets do both:

PowerShell

$Task = Get-ScheduledTask -TaskName "SampleScheduledTask"

$Task.Triggers.Repetition | fl *

As you can see in the following image, the scheduled task's Repetition parameters have the values you provided.

The GUI

As you can see in the following image, the GUI shows that the desired duration and repetition are properly configured.

Wrap Up

In this post I have shown you how to create a scheduled task that will run a PowerShell script and how to modify parameters of the scheduled task that are not available through the Scheduled Tasks PowerShell cmdlets. Using this process you can easily modify practically every parameter of a scheduled task.

BONUS

Attached to this post is a script that will create the scheduled task for you, then run itself every 10 minutes for one day at startup. The usual caveats apply; the script is for demonstration purposes only and do not forget to delete the sample scheduled task that it creates when you are done. To run the attached script, rename it from .txt to .ps1. The script must be placed in a folder called C:\SampleScheduledTaskScript in order to properly run the scheduled task.

SampleScheduledTaskScript.txt

Comments

  • Anonymous
    December 29, 2015
    Shouldn't Microsoft fix this bug so you can specify RepetitionInterval for AtStartup tasks?