#PowerShell, #PowerWiseScripting, #ProjectWise, PWPS_DAB

How To: Create a Scheduled Task Using PowerShell

In this post, I want to share a PowerShell function that I’ve built to quickly create Scheduled Tasks within Windows using the Register-ScheduledJob cmdlet provided with the PSScheduledJob module. I realize this is not ProjectWise related, however, many ProjectWise Administrators run scheduled tasks which process PowerShell scripts to administer ProjectWise.

So why create this function, and why  not simply use the RegisterScheduledJob cmdlet?  My reasoning is this, I only want to create a scheduled task that runs a PowerShell script, typically at a scheduled time each day, and running it immediately to verify everything works properly. Thus, eliminating a lot of the additional parameters available and complexity. It has made the process much easier for myself.

It’s a good idea to look at the help information of the Register-ScheduledJob cmdlet to familiarize yourself with its capabilities.

# Register-ScheduledJob creates a new scheduled task within the 
# Task Scheduler Library \ Microsoft \ Windows \ PowerShell \ ScheduledJobs

# Job definition information is located in the 
#     C:\Users\\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs
#     Example: C:\Users\brian.flaherty\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs

# You can use the following to open the Task Scheduler application
# taskschd.msc

Get-Help Register-ScheduledJob -Full

The following shows that the …\PowerShell\ScheduledJobs does not contain any scheduled tasks.

ts

Now, let’s take a look at the function I’ve created, New-MyScheduledTask. Once imported, you should be able to use the Get-Help to see the help information pertaining to the function. There is a link at the bottom of the post to download a zip file containing the PowerShell script file.

Get-Help New-MyScheduledTask -Full

As you will see, I am using a subset of the available parameters for the Register-ScheduledJob cmdlet and I am limiting it to only use a PowerShell script file. I will  not go through each of the parameters, as the help information will do a better job of it.

The following is a sample script block to run this function.

# Splat containing only the parameters I want to pass to the function.
$Splat_Task = @{
    ScriptFilePath = 'D:\powershell\test_task.ps1'
    TaskName = 'RunMyPowerShellScript'
    Trigger = ( New-JobTrigger -Daily -At "5:00:00 PM" )
    RunNow = $true
}
New-MyScheduledTask @Splat_Task -Verbose

Lets take a look at a few of the parameters which are used in the example.

First, is the $ScriptFilePath parameter. This parameter points to the PowerShell script file to be run by the scheduled task and is required. I am using a ValidateScript block to ensure the file passed exists prior to continuing the function.

<#
    Specifies a script that the scheduled job runs. Enter the path to a .ps1 file on the local computer. To specify default values for the                  
    script parameters, use the ArgumentList parameter. Every Register-ScheduledJob command must use either the ScriptBlock or FilePath                  
    parameters.         
#>
[ValidateScript({ If( Test-Path -Path $_ -PathType Leaf ){ $true } else { Throw "Invalid path given: $_" } })]
[Parameter(
    ParameterSetName = 'FilePath',
    Mandatory = $true)] 
[string] $ScriptFilePath

If the specified PowerShell script file does not exist, you should receive an error similar to the following.

t5

The test_task.ps1 script file listed contains the following. It simply writes the computer name out to the specified text file.

# Contents of the PowerShell script file to be executed by the Scheduled Task.
$env:COMPUTERNAME | Out-File -FilePath d:\temp\Export\test.txt

The following shows that the specified folder ‘d:\TEMP\Export’ does not contain any files.

ts4

Next, is the Trigger parameter. This parameter requires at least one ScheduledJobTrigger object be passed to it or a hashtable containing the job trigger key / value pairs. In the example I am passing a ScheduledJobTrigger to run daily at 5:00 pm. This is an optional parameter.

<# 
    Specifies the triggers for the scheduled job. Enter one or more ScheduledJobTrigger objects, such as the objects that the New-JobTrigger 
    cmdlet returns, or a hash table of job trigger keys and values.

    A job trigger starts the schedule job. The trigger can specify a one-time or recurring scheduled or an event, such as when a user logs on 
    or Windows starts.

    The Trigger parameter is optional. You can add a trigger when you create the scheduled job, use the Add-JobTrigger, Set-JobTrigger, or 
    Set-ScheduledJob cmdlets to add or change job triggers later, or use the Start-Job cmdlet to start the scheduled job immediately. You can 
    also create and maintain a scheduled job without a trigger that is used as a template.

    To submit a hash table, use the following keys:

    `@{Frequency="Once"` (or Daily, Weekly, AtStartup, AtLogon); `At="3am"` (or any valid time string); `DaysOfWeek="Monday", "Wednesday"` 
    (or any combination of day names); `Interval=2` (or any valid frequency interval); `RandomDelay="30minutes"` (or any valid timespan 
    string); `User="Domain1\User01"` (or any valid user; used only with the AtLogon frequency value) }
#>
[Parameter(
    Mandatory = $false )]
[object[]] $Trigger

Finally, the last parameter is RunNow which will execute the scheduled task immediately upon creation.  I typically do this to ensure the process runs and completes successfully.

<#
    Starts a job immediately, as soon as the Register-ScheduledJob cmdlet is run. This parameter eliminates the need to trigger Task
    Scheduler to run a Windows PowerShell script immediately after registration, and does not require users to create a trigger that
    specifies a starting date and time. 
#>
[Parameter(
    Mandatory = $false )]
[switch] $RunNow

When we run the example script block, the schedule task will be created in the PowerShell\ScheduledJobs folder within the Task Scheduler.

ts1ts2

And because we included the RunNow switch parameter, the script was run and a text file was created in the Temp\Export folder as expected.

ts3

Click here to download a zip file containing the ps1 script file.

Again, the following is a link to the full PowerShell script.

Create New Scheduled Job

Experiment with it and have fun.

Hopefully, you find this useful. Please let me know if you have any questions or comments.  If you like this post, please click the Like button at the bottom of the page.

2 thoughts on “How To: Create a Scheduled Task Using PowerShell”

    1. Elahe, you would need to capture those errors within PowerShell using standard PS code then output them to a log file or Event log.

      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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s