Stopping a hanging SCCM Task Sequence

Sometimes it happens that a SCCM Task Sequence is hanging.

You can stop it with this lines of code:

$TS = Get-WmiObject -Namespace root\ccm\SoftMgmtAgent -Class CCM_TSExecutionRequest -Filter "State = 'Completed' and CompletionState = 'Failure'"
 
$TS | ForEach-Object {
    Write-Host "Delete: $($_.MIFPackageName)"
    $_.Delete()
 
}
 
Stop-Service -Name CcmExec
Start-Service -Name CcmExec