<#
.SYNOPSIS
    This function for cleanup of AutoSnap* scheduled tasks that have completed their lifecycle.
.DESCRIPTION
    This function for cleanup of vCenter scheduled tasks named AutoSnap*, all of which have completed their lifecycle.
.NOTES
    Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
    Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
    Test-MyTestFunction -Verbose
    Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>


function Remove-ITDVMwareVMSnapshotTaskExpired {
    [CmdletBinding()]
    param (
        [switch]
        $WhatIf
    )
    
    begin {
        
    }
    
    process {
        Write-Verbose -Message ("Gathering all scheduled tasks with AutoSnap in the task name, this will take some time")
        $si = Get-View ServiceInstance
        $scheduledTaskManager = Get-View $Si.Content.ScheduledTaskManager
        $AllScheduledTasks = Get-View -Id $scheduledTaskManager.ScheduledTask | Where-Object { $_.Info.Name -like "AutoSnap*" } | Select-Object -Unique
        ForEach ($ScheduledTask in $AllScheduledTasks) {
            Write-Verbose -Message ("Start " + $ScheduledTask.Info.Name)
            If ($ScheduledTask.Info.Name -like "AutoSnap*") {
                # Double check snapshot task
                If ($ScheduledTask.Info.PrevRunTime -lt (Get-Date) -and $ScheduledTask.Info.NextRunTime -eq $null) {
                    # if run once and completed
                    
                    If ($WhatIf){
                        Write-Host -Message ("What if: Performing the operation RemoveScheduledTask() on target " + $ScheduledTask.Info.Name)
                    } Else {
                        Write-Verbose -Message ("Removing scheduled task named " + $ScheduledTask.Info.Name)
                        $ScheduledTask.RemoveScheduledTask()
                    }

                    
                }
            }
            Else {
                # do nothing
            }
        }
    }
    
    end {
        
    }
}