Public/MIA/Select-MIATaskSchedule.ps1

function Select-MIATaskSchedule
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory,
                    ValueFromPipeline)]
        [Object[]]$TaskObject,
        [string]$DayOfWeek,
        [string]$StartTime,
        [string]$EndTime = $StartTime
    )

    begin
    {
    }

    process
    {
        foreach ($task in $TaskObject)
        {
            foreach ($schedule in $task.Schedules.Schedule)
            {
                $day = $schedule.Days

                # Filter results by DayOfWeek if specified
                if ($PSBoundParameters.ContainsKey('DayOfWeek')) {
                    if ($DayOfWeek -notin $day.DayOfWeek) {
                        # skip this schedule
                        continue
                    }
                }

                foreach ($interval in $Schedule.Frequency.interval)
                {
                    # Filter results by StartTime and EndTime if specified
                    if ($PSBoundParameters.ContainsKey('StartTime')){
                        #Convert all the start/end times into timespan objects
                        $taskStartTime = (Get-Date -Date $interval.StartTime).TimeOfDay
                        $taskEndTime = (Get-Date -Date $interval.EndTime).TimeOfDay
                        $windowStartTime = (Get-Date -Date $StartTime).TimeOfDay
                        $windowEndTime = (Get-Date -Date $EndTime).TimeOfDay

                        # See https://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap
                        if ( -not ($windowStartTime -le $taskEndTime -and
                                    $windowEndTime -ge $taskStartTime) )
                        {
                            #ranges do not overlap so skip this interval
                            continue
                        }
                    }

                    # Write this task schedule to the pipeline
                    $sched = [PSCustomObject]@{
                        Id = $task.ID
                        Name = $task.Name
                        Scheduled = $task.Scheduled
                        DayOfWeek = $day.DayOfWeek #.substring(0,3) -join ','
                        DayOfMonth = $day.DayOfMonth #-join ','
                        StartTime = $interval.StartTime
                        EndTime = $interval.EndTime
                        EveryMinutes = $interval.EveryMinutes
                    }

                    $sched.PSOBject.TypeNames.Insert(0,'MIREST.MIATaskSchedule')
                    Write-Output $sched
                }
            }
        }
    }

    end
    {

    }
}