Delete scheduled task

Delete a scheduled task

Function Remove-SchedulerTask {
    <#
    .SYNOPSIS
        Delete a scheduled tasks on the local computer.
    .DESCRIPTION
        Delete a scheduled tasks on the local computer using schtasks.exe
    .PARAMETER TaskName
        Specify the name of the scheduled task to remove.
    .PARAMETER ContinueOnError
        Continue if an error is encountered. Default is: $true.
    .EXAMPLE
        Remove-SchedulerTask -TaskName 'Some Task'
    .NOTES
    .LINK
    #>
        [CmdletBinding()]
        Param (
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
            [string]$TaskName,
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
            [boolean]$ContinueOnError = $true
        )
    
        Begin {
            ## Get the name of this function and write header
            [string]${CmdletName} = $PSCmdlet.MyInvocation.MyCommand.Name
            Write-FunctionHeaderOrFooter -CmdletName ${CmdletName} -CmdletBoundParameters $PSBoundParameters -Header
        }
        Process {
            Write-Log -Message "Removing scheduled task [$TaskName]." -Source ${CmdletName}
            Try {
                #  Delete Scheduled Task
                Execute-Process -Path $exeSchTasks -Parameters "/delete /tn $TaskName /f" -WindowStyle 'Hidden'  -CreateNoWindow -ErrorAction 'Stop'
            } 
            Catch {
                Write-Log -Message "Failed to remove scheduled task [$TaskName]." -Severity 3 -Source ${CmdletName}
                If (-not $ContinueOnError) {
                    Throw "Failed to remove scheduled task [$TaskName]."
                }
                Return
            }	
        }
        End {
            Write-FunctionHeaderOrFooter -CmdletName ${CmdletName} -Footer
        }
}
1 Like

Would this be part of the Main-Uninstallation section?

FYI: You can call any function in any section you wish.

(Please post in General Discussion if unsure where to post.)

I personally keep my custom functions in AppDeployToolkitExtensions.ps1

1 Like

Looks like it has issues if there is a space in the task name:

Replacing Try with this seems to work well:

Try {
    #  Delete Scheduled Task
    #Start-Process -Path $exeSchTasks -ArgumentList "/delete /tn $TaskName /f" -NoNewWindow -WindowStyle Hidden -ErrorAction 'Stop'
    $getTask = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
               if($getTask) {
                    cmd /C schtasks.exe /delete /tn $TaskName /f
               }
               else {
                    Write-Log -Message "Scheduled task not found [$TaskName]." -Severity 3 -Source ${CmdletName}
               }
} 
1 Like