'How to delete folder from Task Scheduler with PowerShell?

I can create a Scheduled Task in Windows using the Register-ScheduledTask PowerShell cmdlet with a particular path (i.e., using -TaskPath "\SomePath\" and -TaskName "SomeName"). I can delete the Task using the Unregister-ScheduledTask with the same parameters. I can verify the deletion with the Windows "Task Scheduler" GUI. However, the folder ("\SomePath\") does not get deleted. While this makes perfect sense, I cannot find any way to delete this empty folder.

How do I delete an empty Task Scheduler folder using PowerShell?

UPDATE: After more research, I found another way to solve this problem within PowerShell. It involves working with a Schedule.Service object. Here is the code to delete a folder called 'My Task Folder':

$scheduleObject = New-Object -ComObject Schedule.Service
$scheduleObject.connect()
$rootFolder = $scheduleObject.GetFolder("\")
$rootFolder.DeleteFolder("My Task Folder",$null)


Solution 1:[1]

ScheduledTasks are just xml files which are stored here:

Get-ChildItem -Path 'C:\Windows\System32\Tasks'

You can just delete them from there. They are also referenced from the registry here:

HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache

Just use the...

Remove-Item -Path 'somepath' -Force

... cmdlet as you normally would for any file or folder.

Now of course, if there is a file/folder attribute set, that is preventing the delete, just remove that.

Solution 2:[2]

To delete the task folder called "MEGA" in CMD (or BAT file):

powershell -c "$scheduleObject = New-Object -ComObject Schedule.Service; $scheduleObject.connect(); $rootFolder = $scheduleObject.GetFolder('\'); $rootFolder.DeleteFolder('MEGA',$null)"

Thanks to @jrsrjrsr for Powershell commands.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2