Post

Register Scheduled Task on Windows Task Scheduler

Register Scheduled Task

1
2
3
4
5
6
7
8
$ScriptPath = "$([System.IO.Path]::GetFullPath("$($MyInvocation.MyCommand.Path)\.."))\script"
$TaskName = "CleanData"
$TaskFolder = "\MyApp"

$Trigger = New-ScheduledTaskTrigger -Daily -At 3am
$Action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument "-WindowStyle Hidden -File $ScriptPath\database\clean_data.ps1"
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings (New-ScheduledTaskSettingsSet)
Register-ScheduledTask -TaskName $TaskName -InputObject $Task -TaskPath $TaskFolder -User $(whoami) -Force

Unregister Scheduled Task

1
2
3
4
5
6
7
8
9
$TaskName = "CleanData"
$TaskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $TaskName }

if ($TaskExists) {
    Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
    Write-Host "Scheduled Task $TaskName is removed successfully"
} else {
    Write-Host "Scheduled Task $TaskName is not exist"
}
This post is licensed under CC BY 4.0 by the author.