Create scheduled task in Windows Task Scheduler
Windows Task Scheduler is a utility that helps to execute any process periodically. For example, you want to sync your working files on daily basis, scanning virus, process some data, etc.
A task has the following components:
$task_folder = "\myTasks\"
$task_name = "myTask2"
# this can be any Powershell script.
$ps_script_file = "d:\temp5\test-script.ps1"
## The first line will show err if $task_folder does not exist.
## The second line will not show any err if $task_folder does not exists.
#$exist = Get-ScheduledTask -TaskPath $task_folder | Where-Object {$_.TaskName -eq $task_name}
$exist = Get-ScheduledTask | where {$_.TaskPath -eq "\myTasks\" -and $_.TaskName -eq $task_name }
if (!$exist) {
$axn = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass ""$ps_script_file"""
Register-ScheduledTask -TaskName $task_name -TaskPath $task_folder -Action $axn
Write-Host "created new task"
}
else {
Write-Host "The task already exists"
}
The contents of test-script.ps1
$dt = (get-date).ToString()
Set-Content -Path "d:\temp5\test-ps-output.txt" -Value $dt
A task has the following components:
- Action or multiple actions - which is the process that you want to run periodically. We use New-ScheduledTaskAction to create new action object.
- Trigger - which is the time to run the process and it can have multiple timing. We use New-ScheduledTaskTrigger to create new trigger.
- Security context - any process must run in a valid security context. We can set the context using New-ScheduledTaskPrincipal.
$task_folder = "\myTasks\"
$task_name = "myTask2"
# this can be any Powershell script.
$ps_script_file = "d:\temp5\test-script.ps1"
## The first line will show err if $task_folder does not exist.
## The second line will not show any err if $task_folder does not exists.
#$exist = Get-ScheduledTask -TaskPath $task_folder | Where-Object {$_.TaskName -eq $task_name}
$exist = Get-ScheduledTask | where {$_.TaskPath -eq "\myTasks\" -and $_.TaskName -eq $task_name }
if (!$exist) {
$axn = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass ""$ps_script_file"""
Register-ScheduledTask -TaskName $task_name -TaskPath $task_folder -Action $axn
Write-Host "created new task"
}
else {
Write-Host "The task already exists"
}
The contents of test-script.ps1
$dt = (get-date).ToString()
Set-Content -Path "d:\temp5\test-ps-output.txt" -Value $dt
Comments
Post a Comment