Need help?

Our experts have had an average response time of 11.7 minutes in August 2021 to fix urgent issues.

We will keep your servers stable, secure, and fast at all times for one fixed price.

Manage Scheduled Tasks with PowerShell – Let’s see the details

by | Apr 9, 2021

Wondering how to manage Scheduled Tasks with PowerShell? We can help you.

Most of us use the taskschd.msc graphical interface console to create and manage scheduled tasks on Windows.

However, in various scripts and automated flows, it is much more convenient to use the PowerShell features to create scheduled tasks.

As part of our Server Management Services, we assist our customers with several Windows queries.

Today, let us discuss Scheduled Tasks in detail.

 

Manage Scheduled Tasks on Windows via PowerShell

The ScheduledTasks PowerShell module is to manage scheduled tasks on Windows 10/Windows Server 2016.

To list the cmdlets in a module, we can run:

Get-Command -Module ScheduledTasks
* Disable-ScheduledTask
* Enable-ScheduledTask
* Export-ScheduledTask
* Get-ClusteredScheduledTask
* Get-ScheduledTask
* Get-ScheduledTaskInfo
* New-ScheduledTask
* New-ScheduledTaskAction
* New-ScheduledTaskPrincipal
* New-ScheduledTaskSettingsSet
* New-ScheduledTaskTrigger
* Register-ClusteredScheduledTask
* Register-ScheduledTask
* Set-ClusteredScheduledTask
* Set-ScheduledTask
* Start-ScheduledTask
* Stop-ScheduledTask
* Unregister-ClusteredScheduledTask
* Unregister-ScheduledTask

 

  • Create Scheduled Task with Windows PowerShell

In modern versions of PowerShell, to create them we can use the New-ScheduledTaskTrigger and Register-ScheduledTask cmdlets.

Suppose, we need to create a scheduled task to run at a specific time and execute some PowerShell script or command.

For instance, a scheduled task named StartupScript1 should run the PowerShell script file C:\PS\StartupScript.ps1 at 11:00 AM every day.

The task will execute with advanced privileges (checkbox “Run with highest privileges”) under the SYSTEM account.

$Trigger= New-ScheduledTaskTrigger -At 11:00am -Daily
$User= "NT AUTHORITY\SYSTEM"
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\PS\StartupScript1.ps1"
Register-ScheduledTask -TaskName "StartupScript1" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest –Force

A successful task creation will give us the status “Ready” appears. Now, it will run on the schedule.

If we enable PowerShell Execution Policy on our computer, we can run a PowerShell script from a scheduled task with the –Bypass parameter.

We need to use the below code while creating a new task:

$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument “-NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -File C:\PS\StartupScript.ps1"

For the task to run every time during the computer startup, the first command has to be:

$Trigger= New-ScheduledTaskTrigger -AtStartup

If we want to run a task when a user logs on:

$Trigger= New-ScheduledTaskTrigger -AtLogon

Make sure to open the taskschd.msc console to check a new scheduler task in the Task Scheduler Library.

In Powershell 2.0, to create a scheduled task from PowerShell, we can use the Schedule.Service COM interface.

Here, we create a scheduled task that will execute the specific file containing the PowerShell script during startup. The task performs with the NT AUTHORITY\SYSTEM privileges.

$TaskName = "NewPsTask"
$TaskDescription = "Running PowerShell script from Task Scheduler"
$TaskCommand = "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe"
$TaskScript = "C:\PS\StartupScript.ps1"
$TaskArg = "-WindowStyle Hidden -NonInteractive -Executionpolicy unrestricted -file $TaskScript"
$TaskStartTime = [datetime]::Now.AddMinutes(1)
$service = new-object -ComObject("Schedule.Service")
$service.Connect()
$rootFolder = $service.GetFolder("\")
$TaskDefinition = $service.NewTask(0)
$TaskDefinition.RegistrationInfo.Description = "$TaskDescription"
$TaskDefinition.Settings.Enabled = $true
$TaskDefinition.Settings.AllowDemandStart = $true
$triggers = $TaskDefinition.Triggers
#http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx
$trigger = $triggers.Create(8)

 

  • How to View and Run Scheduled Tasks with PowerShell

We can list all active scheduled tasks on Windows with the command:

Get-ScheduledTask -TaskPath | ? state -ne Disabled

To get information about a specific task:

Get-ScheduledTask CheckServiceState| Get-ScheduledTaskInfo
LastRunTime : 4/7/2021 10:00:00 AM
LastTaskResult : 267011
NextRunTime : 4/8/2021 10:00:00 AM
NumberOfMissedRuns : 0
TaskName : CheckServiceState
TaskPath : \
PSComputerName :
Get-ScheduledTaskInfo powershell

We can disable this task via:

Get-ScheduledTask CheckServiceState | Disable-ScheduledTask

On the other hand, to enable a task:

Get-ScheduledTask CheckServiceState | Enable-ScheduledTask

To run the task immediately (without waiting for the schedule), we run:

Start-ScheduledTask CheckServiceState

Then to completely remove a task from the Task Scheduler library:

Unregister-ScheduledTask -TaskName CheckServiceState

If we need to change the username from which the task launch and for example, the compatibility mode, use the Set-ScheduledTask cmdlet:

$task_user = New-ScheduledTaskPrincipal -UserId woshub\j.abrams' -RunLevel Highest
$task_settings = New-ScheduledTaskSettingsSet -Compatibility 'Win8'
Set-ScheduledTask -TaskName CheckServiceState_PS -Principal $task_user -Settings $task_settings

However, f we receive the error:

Set-ScheduledTask: No mapping between account names and security IDs was done

Make sure the username is correct..

 

  • How to Export and Import Scheduled Tasks via XML Files

With PowerShell we can export the current settings of any scheduled task into a text XML file. Hence, we can export the parameters of any task and deploy it to other computers.

We can export it both from the Task Scheduler GUI and from the PowerShell console.

To export the task with the name StartupScript to the file StartupScript.xml, we run:

Export-ScheduledTask StartupScript | out-file c:\tmp\StartupScript.xml

SInce the Export-ScheduledTask cmdlet is not available in PowerShell 2.0, we use the built-in tool schtasks to export the task settings and redirect the result into a text file:

schtasks /query /tn "NewPsTask" /xml >> "c:\tmp\NewPsTask.xml"

Once the tasks export to the XML file, we can import it to any network computer using the GUI, SchTasks.exe or PowerShell.

Register-ScheduledTask cmdlet can help us to import task settings from an XML file and register it:

Register-ScheduledTask -Xml (Get-Content “\\mun-fs01\public\NewPsTask.xml” | out-string) -TaskName "NewPsTask"

In PowerShell 2.0, it is easier to import a task using the schtasks tool:

schtasks /create /tn "NewPsTask" /xml "\\Srv1\public\NewPsTask.xml" /ru corp\skrutapal /rp Pa$$w0rd
schtasks /Run /TN "NewPsTask"

Take note that this example uses the credentials of the account that is used to run the task. If it doesn’t specify the credentials, because they are not stored in the job, they will request when importing.

[Need hep with the process? We’d be happy to assist]

 

Conclusion

In short, it is much more convenient to use the PowerShell features to create scheduled tasks. Today, we saw how our Support Techs perform this.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = "owonCMyG5nEQ0aD71QM";

0 Comments

Submit a Comment

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

Privacy Preference Center

Necessary

Necessary cookies help make a website usable by enabling basic functions like page navigation and access to secure areas of the website. The website cannot function properly without these cookies.

PHPSESSID - Preserves user session state across page requests.

gdpr[consent_types] - Used to store user consents.

gdpr[allowed_cookies] - Used to store user allowed cookies.

PHPSESSID, gdpr[consent_types], gdpr[allowed_cookies]
PHPSESSID
WHMCSpKDlPzh2chML

Statistics

Statistic cookies help website owners to understand how visitors interact with websites by collecting and reporting information anonymously.

_ga - Preserves user session state across page requests.

_gat - Used by Google Analytics to throttle request rate

_gid - Registers a unique ID that is used to generate statistical data on how you use the website.

smartlookCookie - Used to collect user device and location information of the site visitors to improve the websites User Experience.

_ga, _gat, _gid
_ga, _gat, _gid
smartlookCookie

Marketing

Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user and thereby more valuable for publishers and third party advertisers.

IDE - Used by Google DoubleClick to register and report the website user's actions after viewing or clicking one of the advertiser's ads with the purpose of measuring the efficacy of an ad and to present targeted ads to the user.

test_cookie - Used to check if the user's browser supports cookies.

1P_JAR - Google cookie. These cookies are used to collect website statistics and track conversion rates.

NID - Registers a unique ID that identifies a returning user's device. The ID is used for serving ads that are most relevant to the user.

DV - Google ad personalisation

IDE, test_cookie, 1P_JAR, NID, DV, NID
IDE, test_cookie
1P_JAR, NID, DV
NID
hblid

Security

These are essential site cookies, used by the google reCAPTCHA. These cookies use an unique identifier to verify if a visitor is human or a bot.

SID, APISID, HSID, NID, PREF
SID, APISID, HSID, NID, PREF