Public/Remove-SpecScheduledTask.ps1

Function Remove-SpecScheduledTask {
    <#
    .SYNOPSIS
    Removes scheduled tasks from the local system.
 
    .DESCRIPTION
    The Remove-SpecScheduledTask function removes one or more scheduled tasks from the local system. It uses the Get-ScheduledTask cmdlet to check if the task exists, and if so, it unregisters the task using the Unregister-ScheduledTask cmdlet.
 
    .PARAMETER TaskName
    Specifies the name of the scheduled task to remove. This parameter accepts pipeline input.
 
    .INPUTS
    System.String
 
    .OUTPUTS
    102 - The task was detected, but an error occured trying to remove it.
 
    .EXAMPLE
    PS C:\> Remove-SpecScheduledTask -TaskName "Task1"
    Removes the scheduled task with the name "Task1" from the local system.
 
    .EXAMPLE
    PS C:\> "Task1", "Task2" | Remove-SpecScheduledTask
    Removes multiple scheduled tasks named "Task1" and "Task2" from the local system.
 
    .NOTES
    Author: owen.heaume
    Date: 23-May-2023
    Version: 1.0
    #>


    [CmdletBinding(SupportsShouldProcess = $true)]
    param(
        [Parameter(ValueFromPipeline = $true)]
        [string[]]$TaskName
    )

    Process {
        foreach ($name in $TaskName) {
            $statusCode = Get-SpecScheduledTask -TaskName $name
            if ($statusCode -eq 900) {
                if ($PSCmdlet.ShouldProcess($name, 'Remove')) {
                    try {
                        Unregister-ScheduledTask -TaskName $name -Confirm:$false -ea stop -ev x
                        Write-Verbose "Removed Scheduled Task $name"
                    } catch {
                        write-warning "Although the task was detected, an error occured trying to remove it: $x"
                        return 102
                    }
                }
            } else {
                Write-Warning "The taskname $TaskName does not exist. - No task to delete."
                continue
            }
        }
    }
}