Uninstall Scheduled Task

Hello, I am currently testing the uninstall of my application. I am trying to delete a scheduled task that was created during the install of the application using appdeploytoolkit. When I use the powershell command on the local system it deletes the scheduled task as expected. When I add this powershell script into the Main Uninstallation section of deploy-application.ps1 it doesn’t delete the scheduled task.

Get-ScheduledTask -TaskName "*MyTask*" |Unregister-ScheduledTask -Confirm:$false
´´´

Are you sure the task exists at that point in the script?
Maybe do some checking?
If ($ff=Get-ScheduledTask -TaskName “MyTask”) {Write-Log -Message “$($ff)”}

Hey,

i use a simple extention function

#region Function Manage-ScheduledTask
Function Manage-ScheduledTask {
<#
.SYNOPSIS
	
.PARAMETER TaskName (Task name)
.PARAMETER Action (What to do with schedule task: 'Add','Delete','Query')
.PARAMETER XmlPath (Full path to XML file)
.PARAMETER DeleteExisting (If schedule task already exist, delte before set new task. Default: $false)
.PARAMETER ContinueOnError (Continue if an error is encountered. Default: $true)
.EXAMPLE
	Manage-ScheduledTask -Action "Add" -TaskName "OneDrive" -XmlPath "$dirFiles\OneDrive.xml" -DeleteExisting $true
	Manage-ScheduledTask -Action "Delete" -TaskName "OneDrive" -ContinueOnError $false
	Manage-ScheduledTask -Action "Query" -TaskName "OneDrive" -ContinueOnError $false
.NOTES
#>
    [cmdletbinding()]
    Param (
        [parameter(Mandatory=$true)]
		[ValidateNotNullOrEmpty()]
		[string]$TaskName,
        [ValidateSet('Add','Delete','Query')]
		[string]$Action,
		[Parameter(Mandatory=$false)]
        [string]$XmlPath = $null,
        [boolean]$DeleteExisting = $false,
        [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
 		$ErrorActionPreference = "Stop" 
        [string]$Parameter = ""
        [int32]$returnCode = 70015
    }

    Process {
        Write-Log -Message "Try to manage scheduled task." -Source ${CmdletName}
        If (!(Test-Path -Path $exeSchTasks -PathType Leaf)) {
            Write-Log -Message "Schedule task executable [$exeSchTasks] not found." -Severity 3 -Source ${CmdletName}
            If (-not $ContinueOnError) {
                Exit-Script -ExitCode $returnCode
            }
            Return $false
        }

        ## Help function to run commands
        Function SchedTask-Execute {
            Try {
                Write-Log -Message "Executing [$exeSchTasks $Parameter]..." -Source ${CmdletName}
                $Process = Start-Process -FilePath $exeSchTasks -ArgumentList $Parameter -PassThru -WindowStyle Hidden
                Wait-Process -InputObject $Process
                If ($Process.ExitCode -eq 0) {
                    Write-Log -Message "Execution completed successfully with exit code [$($Process.ExitCode)]." -Source ${CmdletName}
                    Start-Sleep -Seconds 3
                } Else {
                    Throw "Execution failed with exit code [$($Process.ExitCode)]."
                }
            } Catch {
                Write-Log -Message $_.Exception.Message -Severity 3 -Source ${CmdletName}
                If (-not $ContinueOnError) {
                    Exit-Script -ExitCode $returnCode
                }
            }
        }
        ## End help fuctions

        $GetScheduledTask = $null       
        $GetScheduledTask = Get-SchedulerTask -TaskName "$($TaskName)" -ContinueOnError $false
        If ($GetScheduledTask) {
            $CleanTaskName = $GetScheduledTask.TaskName
            If ($CleanTaskName.StartsWith("\")) {
                $CleanTaskName = $CleanTaskName.TrimStart("\")
            }

            If ($CleanTaskName -like "$($TaskName)") {
                Write-Log -Message "Schedule task [$($CleanTaskName)] exist, task state is [$($GetScheduledTask.Status)]." -Source ${CmdletName}
                $TaskExist = $true
            } Else {
                Write-Log -Message "Schedule task [$($CleanTaskName)] doesn't exist." -Source ${CmdletName}
                $TaskExist = $false
            }
        } Else {
            Write-Log -Message "Schedule task [$($TaskName)] doesn't exist." -Source ${CmdletName}
            $TaskExist = $false
        }

        Switch ($Action) {
            "Add" {   
                If ($DeleteExisting -and $TaskExist) {
                    Write-Log -Message "Delete existing scheduled task [$($CleanTaskName)`]." -Source ${CmdletName}
                    [string]$Parameter = "/Delete /TN `"$($CleanTaskName)`" /F"
                    SchedTask-Execute
                }

                Write-Log -Message "Add schedule task [$($TaskName)]." -Source ${CmdletName}
                [string]$Parameter = "/Create /XML `"$($XmlPath)`" /TN `"$($TaskName)`" /F"
                SchedTask-Execute 
                Break
            }
            "Delete" {
                If ($TaskExist) {
                    Write-Log -Message "Delete schedule task [$($TaskName)]." -Source ${CmdletName}
                    $Parameter = "/Delete /TN `"$($TaskName)`" /F"
                    SchedTask-Execute
                }
                Break
            }
            "Query" {
                Return $GetScheduledTask
                Break
            }
        }
    }

    End {
        Write-FunctionHeaderOrFooter -CmdletName ${CmdletName} -Footer
    }

}
#endregion

Thanks for the replies. This is my first application I am deploying with SCCM using appdeploytoolkit. I have 3 collections: install available, install required, uninstall
When I add a computer to the uninstall collection it successfully removes folders but doesn’t delete the scheduled task. I have included the section of code in deploy-application.ps1.

#*====================================PRE-UNINSTALLATION END==================================================================
	#endregion PRE-UNINSTALLATION

	#region MAIN-UNINSTALLATION
		[string]$installPhase = 'Uninstallation'
		#*====================================MAIN-UNINSTALLATION BEGIN===============================================================

		# user dialogs (deprecated)
		if ($Company_UseDialogs){
			## Only use for longer installations (Installation duration approx. >3 minutes)
			#Show-InstallationProgress -WindowLocation 'BottomRight'
		}
        Get-ScheduledTask -TaskName "*MyTask*" |Unregister-ScheduledTask -Confirm:$false
		
	    If (Test-Path -Path "$envProgramData\Company\DeleteProfiles"){
        
            Remove-Folder -Path "$envProgramData\Company\DeleteProfiles"
         
        }


		#*====================================MAIN-UNINSTALLATION END==================================================================
	#endregion MAIN-UNINSTALLATION

	#region POST-UNINSTALLATION
		[string]$installPhase = 'Post-Uninstallation'
		#*====================================POST-UNINSTALLATION BEGIN===============================================================
			
        # application entry
		Remove-ApplicationWizardEntry
		
		##Branding Uninstall
		Remove-Branding
	
		##Handling for required reboot   
        #Set-Reboot

		#*====================================POST-UNINSTALLATION END=================================================================
	#endregion POST-UNINSTALLATION

#endregion UNINSTALLATION

You are not logging anything by piping it.

At a minimum, you should break it up:

$MyTask = Get-ScheduledTask -TaskName "*MyTask*" 
If ($null -ne $MyTask ) {
   $MyTask | Unregister-ScheduledTask -Confirm:$false
} Else {
   write-log "[*MyTask*] was not found."
}

If you want to try to log more, you can look here:
Logging for non-PSADT commands - The Toolkit / Tips & Tricks - PSAppDeployToolkit Community

@That-Annoying-Guy Thanks for the note. I tried the suggested script and it deleted every scheduled task on the computer. I was hoping to only delete the task named MyTask.

Sorry about that.
I updated one line in my previous post.
I forgot to use the $MyTask variable with Unregister-ScheduledTask cmdlet.

Not a problem at all. I am happy someone was willing to help!
The task is unregistered according to the log. What I can’t figure out is why it still shows in the Task Scheduler GUI. Also when I look in c:\Windows\System32\Tasks there is still a folder there named MyTask. When I try to delete it i am given an error that the file cannot be found.
I used my admin account to create the task and admin account to unregister the account. It is very strange.

Maybe the task you want to delete is in a folder and the Unregister-ScheduledTask cmdlet sees that the task doesn’t exist and takes credit for a job well done.

Maybe try to remove your task without PSADT involved.

Yes, you are correct. I tried earlier to run the command just from powershell and it worked beautifully. The task “MyTask” is located at the root level, maybe this is the problem when using appdeploytoolkit? I have exhausted my knowledge. :frowning: