AzureSqlMaintenancePlan.psm1

function Confirm-Schedule {
    param (        
        [Parameter(Mandatory = $True)]
        [string]$Schedule,
        [Parameter(Mandatory = $True)]
        [string]$ScheduleTimeZone,
        [Parameter(Mandatory = $False)]
        [string]$Database
    )

    # https://jorgklein.com/2017/09/19/azure-sql-database-scheduled-autoscaling/

    # Get current date/time and convert to $ScheduleTimeZone.
    $scheduleData = $schedule | ConvertFrom-Json
    $i = 0
    foreach ($item in $scheduleData) {
        Add-Member -InputObject $item -NotePropertyName "Id" -NotePropertyValue $i
        $i++
    }
    $start = Get-Date # Azure Automation local time
    $toTimeZone = [System.TimeZoneInfo]::FindSystemTimeZoneById($scheduleTimeZone)
    $start = [System.TimeZoneInfo]::ConvertTime($start, $toTimeZone)
    $dayOfWeek = [int]($start).DayOfWeek
 
    # Get the scaling schedule for the current day of week.
    $matchingByDate = $scheduleData | 
    Where-Object { $_.WeekDays -contains $dayOfWeek } | 
    Select-Object  `
    Id,
    WeekDays,
    Database,
    @{Name = "StartTime"; Expression = { [datetime]::ParseExact(($start.ToString("yyyy:MM:dd") + ":" + $_.StartTime), "yyyy:MM:dd:HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) } }, `
    @{Name = "StopTime"; Expression = { [datetime]::ParseExact(($start.ToString("yyyy:MM:dd") + ":" + $_.StopTime), "yyyy:MM:dd:HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture) } }

    if ($null -ne $matchingByDate) { 
        # Schedule found for this day.
        # Get the schedule for the current time. If there is more than one available, pick the first.
        $matchingByTime = $matchingByDate | 
        Where-Object { (($null -eq $_.Database) -or ($_.Database -eq $Database)) -and ($start -ge $_.StartTime) -and ($start -lt $_.StopTime) } | 
        Sort-Object `
        -Property @{Expression = { $_.Database }; Ascending = $false }, `
        @{Expression = { $_.Id }; Ascending = $true }  | 
        Select-Object -First 1
        if ($null -ne $matchingByTime) {
            return $matchingByTime;
        }
    }
}