Wednesday, July 10, 2019

Powershell Scheduled Tasks

Here is a script to create a scheduled task via powershell and run as a specific user.  This can be useful when using a Core server that you can't create the scheduled task through the GUI, or if you want to add the scheduled task to source control.

<#example of how to do this with the schtasks command
schtasks /create /tn "TaskName" /tr "powershell.exe -file c:\scripts\script.ps1" /sc DAILY /st 22:00:00 /ru "System"
#>

$name = 'TaskName'
$runAt = '10:00 PM'
$exe = 'powershell.exe'
$params = '-file script.ps1'
$location = 'C:\scripts\'

<# if you want, you can delete an existing task.
Unregister-ScheduledTask -TaskName $name -TaskPath $taskPath -Confirm:$false -ErrorAction:SilentlyContinue  
#>


$action = New-ScheduledTaskAction -Execute "$exe" -Argument "$params" -WorkingDirectory "C:\scripts"
$trigger = New-ScheduledTaskTrigger -Daily -At $runAt
Register-ScheduledTask -TaskName $name -TaskPath "\" -Action $action -Trigger $trigger -User 'System'  | Out-Null


This will create a task that runs the powershell script c:\scripts\script.ps1 every day at 10 PM and it will run as the System user.