How to Set Up and Manage Scheduled Tasks with PowerShell

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

In Windows 10, Microsoft’s new command line tool is built-in and ready to use. In this article, I’ll show you how to set up scheduled tasks on your computer with PowerShell.

The “new-scheduledtasktrigger” is a PowerShell command that allows users to create scheduled tasks. The task can be set up to run automatically or on a timer.

How to Set Up and Manage Scheduled Tasks with PowerShell

Do you need to generate a large number of scheduled activities or automate the process of creating scheduled tasks? If that’s the case, you’re in luck. In this tutorial, you’ll learn how to use PowerShell to handle scheduled activities.

Using the Task Scheduler app interface, you can create scheduled tasks that execute basic things quickly and easily (GUI). System administrators or developers, on the other hand, may be required to deploy more complex jobs with numerous schedules, triggers, or parameters.

Fortunately, PowerShell can be used to create and manage scheduled activities. The ScheduledTasks module, which is included with Windows, may be used to manage scheduled tasks using PowerShell.

Prerequisites

There are certain requirements to follow along with this post since it is a learning-by-doing kind. The prerequisites for creating PowerShell scheduled tasks using PowerShell are shown below.

  • This article’s examples are based on Windows 10. Windows Server 2012 and newer, on the other hand, can perform the same thing.
  • PowerShell 5.1 or PowerShell 7 are the two versions of Windows PowerShell available.
  • A script editor, such as Visual Studio Code, Notepad++, or Windows PowerShell ISE, would be beneficial.

Adding a New Task to a Schedule

To operate, a scheduled job must have at least two components: action and trigger. It’s up to you if you want to add a security context and a set of relevant parameters. Refer to the short explanations for each planned task component below for a better understanding:

  • The planned task’s action is the action that is carried out. A common action is to execute a program or a script. There may be several actions in a scheduled task.
  • Trigger – determines when the scheduled task is executed. Triggers may be time-based, such as creating a daily or hourly recurring schedule. Triggers may also be activity-based, in which a task is executed in response to identified actions such as computer starting, user login, or logged events.
  • The security context used to perform the scheduled job is controlled by the principal. A principal comprises the user account and the needed privilege utilized by the scheduled job, among other things.
  • Settings – are a collection of parameters and circumstances that influence the behavior of the scheduled job. You may, for example, set a task to be eliminated after a certain number of days if it is left unattended.

The principal and settings are not needed for the establishment of a scheduled job. Instead, the default settings are utilized.

Creating a Task Action is a process that involves putting together a list of

Create a new task action when you want a scheduled task to perform something. In this example, you’ll construct a task that runs a script by using PowerShell.exe. Make sure your script editor is up to date.

Please keep in mind that the script below is only an example; you are not obligated to use it. You are free to use whatever script you like. Using the script below, on the other hand, produces an easily verifiable output that can be used to check if the scheduled operation was completed.

When the sample script is run, it retrieves the top ten most recent occurrences from the application event log. Then, in the c:temp folder, export the events to a new XML file. Copy and paste the code below into your script editor, then save it as Get-LatestAppLog.ps1 in whichever folder you desire.

# Get-LatestAppLog.ps1 is a PowerShell script that retrieves the most recent version of an application. ## Create a log file. ‘c:temp’ as $logDir $logFile = “$logDirAppLog $(Get-Date -format ‘yyyy-mm-dd hh-mm-ss-tt’).xml” $logDirAppLog $(Get-Date -format ‘yyyy-mm-dd hh-mm-ss-tt’).xml ## Obtain the most recent 10 application log events. Export-CliXml | Get-WinEvent -LogName application -MaxEvents 10 | Get-WinEvent -LogName application -MaxEvents 10 -Force $logFile

The New-ScheduledTaskAction method is used to generate a new scheduled-task action object in the $taskAction variable. This operation will launch the powershell.exe program with the input C:scriptsGet-LatestAppLog.ps1 as the argument.

# Make a new action for a task. $taskAction = New-ScheduledTaskAction’-Execute ‘powershell.exe”-Argument ‘-File C:scriptsGet-LatestAppLog.ps1′ $taskAction = New-ScheduledTaskAction’-Execute ‘powershell.exe”-Argument ‘-File C:scriptsGet-LatestAppLog.p $taskAction

Copy and paste the command above into PowerShell. The $taskAction variable should now contain an object that looks like the screenshot below.

Adding a New Task to a Schedule ActionAdding a New Task to a Schedule Action

Including a Trigger in the Mix

After you’ve defined a task action, the following step is to specify when it must execute. The New-ScheduledTaskTrigger cmdlet should be used to create a trigger. The command below generates a daily 3 p.m. trigger. In PowerShell, copy and execute the code.

# Make a brand-new trigger (Daily at 3 AM) $taskTrigger = New-ScheduledTaskTrigger -Daily -At 3PM; $taskTrigger = New-ScheduledTaskTrigger -Daily -At 3PM; $taskTrigger = $tasktrigger

The $tasktrigger variable’s resultant object should resemble the picture below.

How to Make a Trigger (Daily at 3 AM)How to Make a Trigger (Daily at 3 AM)

Getting the Job Done

So far, you’ve set up the foundation for creating a new scheduled job. The next step is to create and register the scheduled task in the system.

The Register-ScheduledTask cmdlet is used to register the scheduled task in the code below. The -Action option is required to supply the task action object that is kept in the $taskAction variable. The -Trigger option is required to send the contents of the $taskTrigger variable.

# Create a new PowerShell scheduled task # Give your scheduled task a name. # Describe the scheduled job using $taskName = “ExportAppLog” # Register the scheduled job $description = “Export the 10 most recent events in the application log” -TaskName Register-ScheduledTask -Action $taskName -Trigger $taskAction $taskAction $taskAction $taskAction $taskAction $taskA -Description $taskTrigger $taskTrigger $taskTrigger $taskTrigger $taskTrigger $taskTri $description

Copy and execute the code above in PowerShell. As a consequence, as seen below, a new scheduled job is created.

The new scheduled task is being registered.The new scheduled task is being registered.

Performing the Task

After you’ve created a scheduled task, double-check that it’s still there in the system. Open the Job Scheduler and go through the list for the scheduled task. The registered task should appear in the list.

The Task Scheduler app shows the new scheduled task.The Task Scheduler app shows the new scheduled task.

You may alternatively use the PowerShell command below to see whether the scheduled job is registered.

ExportAppLog Get-ScheduledTaskInfo -TaskName

After that, you should see something similar to the snapshot of the outcome below.

Obtaining information about the scheduled job.Obtaining information about the scheduled job.

Finally, your new planned duty should be determining whether or not everything you’ve done so far has been successful. You may either wait for the next planned run or manually initiate the scheduled job using the command below.

ExportAppLog -TaskName Start-ScheduledTask

You should get a result similar to the one shown below after executing the code. As you can see, executing the code resulted in the creation of an XML file, indicating that the scheduled operation completed successfully.

Performing the Task That Was ScheduledPerforming the Task That Was Scheduled

Changing a Scheduled Task that Has Already Been Completed

Some features of a scheduled task may need to be updated after it is created. Perhaps you’d want to start it an hour sooner or adjust the script’s location. These are some of the possible modifications to the scheduled job.

In the following sections, you’ll learn how to use PowerShell to make modifications to already-registered scheduled activities.

User Account, Security Options, and Compatibility Settings may all be changed.

The scheduled job in the preceding section executes within the same user account context that generated it. What if the job requires the usage of a different user account, such as a service account?

In this example, you’ll change the security choices for the scheduled job to the values shown below.

  • To perform the scheduled activity, you must update the user account.
  • Allow the job to execute regardless of whether or not the user is signed in.
  • Run it with the most privileges possible.
  • The task’s compatibility should be set to Windows 10.

The first line of code creates a principal object for the new user account and sets the task to execute with the maximum rights. Make sure the -UserID parameter is set to the correct value. The task’s compatibility with Windows 10 is configured on the second line.

Finally, the final line uses the settings saved in the $taskPrincipal and $taskSettings variables to update the ExportAppLog **scheduled task. Copy and execute the code below in PowerShell.

# Set the user ID and run level for the task principal. $taskPrincipal = New-ScheduledTaskPrincipal -UserId ‘DEVPCsvcTask’ -RunLevel Highest $taskPrincipal = New-ScheduledTaskPrincipal -UserId ‘DEVPCsvcTask’ -RunLevel Highest $taskPrincipal = # Set Windows 10 as the task compatibility value. $taskSettings = New $taskSettings = New $taskSettings = New -Compatibility Win8 -ScheduledTaskSettingsSet # Change the task’s primary settings. ‘ExportAppLog’ -TaskName ‘Set-ScheduledTask’ -Principal -Settings $taskPrincipal $taskSettings

The -Compatibility option value is Win8 as you can see. Don’t be perplexed. Since Windows 8, it seems that Microsoft has not updated the “latest” version choices. Using the Win8 value, however, will result in Windows 10 compatibility.

The following command updates the current ExportAppLog **scheduled job using the Set-ScheduledTask cmdlet. Change the password value in the -Password argument to the right password for the user account.

# Change the password and user account for the task user. Set-ScheduledTask -TaskName ‘ExportAppLog’ -User $taskPrincipal Set-ScheduledTask -TaskName ‘ExportAppLog’ Set-ScheduledTask -TaskName ‘Ex PASSWORD -UserID -UserID -UserID -UserID -U

The scheduled job is updated after performing the aforesaid command. You can validate that the security choices have changed by checking the scheduled task.

The security option, the user account, and the compatibility options are all available.The security option, the user account, and the compatibility options are all available.

Changing the Trigger Mechanism

The trigger schedule may need to be adjusted on occasion. Perhaps as a result of certain operational changes or resource optimization. You may use PowerShell to change or add triggers to a scheduled job in any scenario.

ExportAppLog is now initiated every day at 3 p.m. via a scheduled job. Assume you need to adjust the trigger schedule to 4:30 p.m. and 1:00 a.m. every day. For the two schedules, you must first build two new task trigger objects.

$taskTrigger1 = New-ScheduledTaskTrigger -Daily -At 4:30PM $taskTrigger1 = New-ScheduledTaskTrigger -Daily -At 4:30PM $taskTrigger1 = New $taskTrigger2 = New-ScheduledTaskTrigger -Daily -At 1:00AM $taskTrigger2 = New-ScheduledTaskTrigger -Daily -At 1:00AM $taskTrigger2 = New

Then use the command below to adjust the scheduled task’s trigger. The -Trigger argument allows two task trigger objects, $taskTrigger1 and $taskTrigger2, as you can see.

You’ll also need to enter the -User and -Password values again since you’re changing a scheduled job with a password kept for the user account.

Set-ScheduledTask -TaskName ‘ExportAppLog’ -Trigger Set-ScheduledTask -TaskName ‘ExportAppLog’ -Trigger Set-ScheduledT -User ‘DEVPCsvcTask’ -Password ‘PASSWORD’ $taskTrigger1,$taskTrigger2

The expected outcome after running the code is shown below.

Multiple triggers are used to update the scheduled job.Multiple triggers are used to update the scheduled job.

The ExportAppLog scheduled job now has two triggers, as you can see below.

Multiple triggers on a scheduled jobMultiple triggers on a scheduled job

A Scheduled Task Can Be Deleted and Restored

Over time, scheduled tasks may become outdated. You may need to do housekeeping for scheduled chores at some time. You’ll learn how to delete scheduled tasks in PowerShell in this section.

Creating a Backup of a Scheduled Task

It’s a good idea to create a backup before you start eliminating scheduled activities. When you back up scheduled tasks, you have a restoration point in case anything goes wrong.

There is no built-in cmdlet for backing up a scheduled operation. However, everything in PowerShell is an object, and you can export objects to a file. Use the Export-Clixml cmdlet to save a copy of an object to a file.

The sample code below creates a file from the scheduled job named ExportAppLog. You may customize the filename and location to your liking.

# Get-ScheduledTask ‘ExportAppLog’ -TaskName | Export-Clixml c:tempExportAppLog.xml # Export the scheduled task object to XML

The intended output XML file is shown in the figure below.

Creating a Backup of a Scheduled TaskCreating a Backup of a Scheduled Task

Getting Rid of a Scheduled Task

You may now delete the scheduled job once you’ve made a backup of it. The following code removes the ExportAppLog scheduled job. Copy and execute the code below in PowerShell.

# Remove the scheduled task from the list of tasks. Unregister-ScheduledTask -TaskName ‘ExportAppLog’ -Confirm:$false Unregister-ScheduledTask -TaskName ‘ExportAppLog’ -Confirm:$false

It’s usually a good idea to double-check the outcome of the scheduled job deletion, even if it’s not necessary. Verify that the scheduled job no longer exists using the command below.

Get-ScheduledTask ‘ExportAppLog’ -TaskName

You should obtain an output similar to the one below if the scheduled job no longer exists.

Checking to see whether the scheduled job is still activeChecking to see whether the scheduled job is still active

Passwords are not included in the scheduled job backup.

Getting a Scheduled Task Back

So you removed a scheduled task, only to discover that you weren’t meant to! So, what’s next? This kind of event increases your appreciation for the notion of backups.

Using PowerShell and the XML backup file, you may rebuild the scheduled task. And here’s how you can go about doing it.

To begin, open your PowerShell session and import the XML backup. The following code imports the c:tempExportAppLog.xml file. As a consequence, the imported data will be stored in the $stBackup variable.

# Import the backup of the Schedule Task Import-Clixml -Path c:tempExportAppLog.xml $stBackup

Then, using the code below, change the LogOnType value of the task principal to Interactive. The LogonType value must be reset in order for the scheduled job to be restored successfully.

# Change the logon type to “Only run when the user is logged in.” $stBackup.Principal.LogonType = ‘Interactive’ $stBackup.Principal.LogonType = ‘Interactive’

Create a new Scheduled Task object as the following step. The following code generates a new scheduled job. The resultant scheduled task object is stored in the $restoreTask variable.

The values supplied to the parameters are the ones imported from backup, as you can see. The $restoreTask variable contains the imported values. Action, Trigger, Settings, and Principal are the parameters.

# Use the imported variables to create a new Scheduled Task object. $restoreTask = New-ScheduledTask’-Action $stBackup.Actions’-Trigger $stBackup.Triggers’-Settings $stBackup.Settings’-Principal $stBackup.Principal $stBackup.Principal $stBackup.Principal $stBackup.Principal $

It’s time to register the scheduled task once you’ve created the scheduled task object. To register the restored scheduled job, use the code below.

The task name in this case is ‘ExportAppLog restored.’ The scheduled task object in the $restoreTask variable is accepted by the InputObject argument. Make sure you’re using the right user and password.

‘ -TaskName ‘ExportAppLog restored”-InputObject $restoreTask’-User ‘DEVPCsvcTask”-Password ‘PASSWORD’

The code is now finished. To restore the deleted scheduled task, copy and execute the code in PowerShell. The intended outcome after executing the code is shown in the image below.

Using an XML backup to restore a deleted scheduled jobUsing an XML backup to restore a deleted scheduled job

The system has now registered the scheduled task. The restored scheduled job is shown in the image below.

locating the re-scheduled tasklocating the re-scheduled task

Summary

Windows’ Scheduled Tasks function is a fantastic tool for creating tasks and jobs. You may build assignments ranging from the most simple to the most complicated. The choices and settings are adaptable.

The PowerShell Scheduled Tasks module allows you to create scheduled tasks using PowerShell commands. This module gives you the ability to dynamically create and deliver scheduled tasks on local and distant machines.

The ScheduledTasks module hasn’t been updated in a while, and several complex options aren’t currently readily accessible via PowerShell cmdlets. Creating a trigger for “On workstation unlock” is one example. However, you may use the existing task scheduler CIM class to obtain these complex parameters.

Nonetheless, you may add the PowerShell Scheduled Tasks module to your PowerShell arsenal as a good and powerful utility.

References

The “powershell create scheduled task for all users” is a command that can be used to set up and manage scheduled tasks. This will allow you to schedule tasks in the future, or even now.

Frequently Asked Questions

How do I create a scheduled task in PowerShell?

A: Using PowerShell, you can schedule a task to run at a specific time. To do this, open up your PowerShell window and type in the following command –
powershell -file C:\scriptname.ps1

How do you automate a task in PowerShell?

A: To automate a task in PowerShell, you write it down. This will be your scheduled process. You then run the command by using at the start of the code and space-bar to enter into input mode . From there, you can use tab completion for commands that have parameters or variables.

How do I view scheduled tasks in PowerShell?

A: To view scheduled tasks in PowerShell, use the Get-ScheduledTask cmdlet. Search for the task with a name and description that matches what you are looking for to find it.

Related Tags

  • new-scheduledtaskprincipal
  • powershell create scheduled task to run as logged on user
  • register-scheduledtask
  • powershell create scheduled task on remote computer
  • new-scheduledtaskaction

Table of Content