Public/MIA/Select-MIATaskSchedule.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
    {

    }
}