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