Functions/Import-BsgPbiDatasetSchedule.ps1

<#
    .SYNOPSIS
        Import Power BI dataset schedule from a json file.
         
    .DESCRIPTION
        The schedule definition is imported from a JSON file into a workspace and the corresponding dataset.
 
    .PARAMETER Target_WorkspaceId
        The id of the workspace you would like to import the schedule.
        You can find it in the Power BI workspace URL.
 
    .PARAMETER Target_DatasetId
        The id of the target dataset, where you would like to import the schedule.
        You can find it in the Power BI dataset URL.
 
    .PARAMETER Source_DatasetId
        The id of the source dataset of which the schedule was exported.
        You can find it in the Power BI dataset URL or in the exported file.
 
    .PARAMETER Path_Workspace
        The path to the workspace folder, where the schedule information is stored.
        Subfolders will be created automatically.
 
    .PARAMETER Is_Refreshable
        Wether the schedule is a refresh Schedule (Import) or not refreshable (Direct Query, Live Connection etc.).
 
    .EXAMPLE
        # Import schedule Import
        Import-BsgPbiDatasetSchedule -Target_WorkspaceId 15ebfcd7-1aa9-4c3d-8963-46c3812a559a -Target_DatasetId 4837389a-a104-4701-8039-1bb4645644d7 -Source_DatasetId 827f8cd5-808d-4ef2-883e-e8730a39cf06 -Path_Workspace "C:\temp\BSG PBI Administration\Backup\Workspaces\BSGroup DA - Test Workspace" -Is_Refreshable $true
 
        # Import schedule Direct Query
        Import-BsgPbiDatasetSchedule -Target_WorkspaceId 15ebfcd7-1aa9-4c3d-8963-46c3812a559a -Target_DatasetId 4837389a-a104-4701-8039-1bb4645644d7 -Source_DatasetId 791be759-9a8d-4e05-85b3-ecbb7d653019 -Path_Workspace "C:\temp\BSG PBI Administration\Backup\Workspaces\BSGroup DA - Test Workspace" -Is_Refreshable $false
 
    .INPUTS
 
    .OUTPUTS
 
    .NOTES
        This script uses the Power BI Management module for Windows PowerShell. If this module isn't installed, install it by using the command 'Install-Module -Name MicrosoftPowerBIMgmt -Scope CurrentUser'.
#>


function Import-BsgPbiDatasetSchedule{
    param(
        [Parameter(Mandatory=$true)][string]$Target_WorkspaceId, 
        [Parameter(Mandatory=$true)][guid]$Target_DatasetId,
        [Parameter(Mandatory=$true)][guid]$Source_DatasetId,
        [Parameter(Mandatory=$true)][string]$Path_Workspace,
        [Parameter(Mandatory=$true)][bool]$Is_Refreshable
    )
    
    try{

        # Define paths, filenames and URLs
        if ($Target_WorkspaceId -eq 'me'){
            $Target_WorkspaceUrl = "https://api.powerbi.com/v1.0/myorg"
        } else{
            $Target_WorkspaceUrl = "https://api.powerbi.com/v1.0/myorg/groups/" + $Target_WorkspaceId
        }
        $Target_DatasetUrl = $Target_WorkspaceUrl + "/datasets/" + $Target_DatasetId
        $Path_Datasets = Join-Path -Path $Path_Workspace -ChildPath 'Datasets'

        if ($Is_Refreshable){
            # Write-PSFMessage -Level Verbose -Message 'Importing refresh schedule...'
            $Path_Schedules = Join-Path -Path $Path_Datasets -ChildPath "refreshSchedules"
        } else{
            # Write-PSFMessage -Level Verbose -Message 'Importing not refreshable schedule...'
            $Path_Schedules = Join-Path -Path $Path_Datasets -ChildPath "directQueryRefreshSchedules"
        }

        # Define schedule metadata filename
        $FileName_ScheduleMetadata = Get-ChildItem -Path $Path_Schedules -Name "*$Source_DatasetId.json"
        $Path_ScheduleMetadata = Join-Path -Path $Path_Schedules -ChildPath $FileName_ScheduleMetadata


        # ===
        # Get Schedule metadata file
        # =

        try{
            
            # Check path
            if ((Test-Path $Path_Schedules) -eq $false){
                throw "Path `"$Path_Schedules`" does not exist."
            }

            # Check mapping file
            if ((Test-Path $Path_ScheduleMetadata) -eq $false){
                throw "File does not exist is folder `"$Path_Schedules`"."
            }
            $ScheduleObject = Get-Content -Path $Path_ScheduleMetadata | ConvertFrom-Json -ErrorAction Stop

        } catch{
            throw "Error while getting schedule metadata file `"$FileName_ScheduleMetadata`". `n$_"   
        }



        # ===
        # Update schedule depending on type of schedule
        # =
        
        if ($Is_Refreshable){

            # ===
            # Import schedule
            # =

            # Define RequestURL
            $Target_RequestUrl = $Target_DatasetUrl + "/refreshSchedule"

            # ===
            # Activate schedule (need to be in seperate API-Call!)
            # =

            # Create new JSON body request
            $RequestBody = $ScheduleObject | Select-Object enabled
            $RequestBody = [PSCustomObject]@{
                "value" = $RequestBody
            }
            $RequestBody = $RequestBody | ConvertTo-Json

            # API-call
            try{
                $response = Invoke-PowerBIRestMethod -Url $Target_RequestUrl -Method Patch -Body $RequestBody -ErrorAction Stop
            } catch{
                throw "Error after calling request URL: $Target_RequestUrl. `n$_"
            }


            # ===
            # Update schedule details (need to be in seperate API-Call!)
            # =

            # Create new JSON body request
            $RequestBody = $ScheduleObject | Select-Object days , times, localTimeZoneId, notifyOption
            $RequestBody = [PSCustomObject]@{
                "value" = $RequestBody
            }
            $RequestBody = $RequestBody | ConvertTo-Json

            # API-call
            try{
                $response = Invoke-PowerBIRestMethod -Url $Target_RequestUrl -Method Patch -Body $RequestBody -ErrorAction Stop
            } catch{
                throw "Error after calling request URL: $Target_RequestUrl. `n$_"
            }

        } else{

            # ===
            # DirectQuery schedule
            # =

            # Define RequestURL
            $Target_RequestUrl = $Target_DatasetUrl + "/directQueryRefreshSchedule"

            # Create new JSON body request
            $RequestBody = $ScheduleObject | Select-Object frequency, days, times, localTimeZoneId
            $RequestBody = [PSCustomObject]@{
                "value" = $RequestBody
            }
            $RequestBody = $RequestBody | ConvertTo-Json

            # API-call
            try{
                $response = Invoke-PowerBIRestMethod -Url $Target_RequestUrl -Method Patch -Body $RequestBody -ErrorAction Stop
            } catch{
                throw "Error after calling request URL: $Target_RequestUrl. `n$_"
            }

        }

        # Message
        if ($Is_Refreshable){
            # Write-PSFMessage -Level Host -FunctionName "Import-BsgPbiDataset" -Message " Refreshable schedule updated."
            # Write-PSFMessage -Level Verbose -FunctionName "Import-BsgPbiDataset" -Message " Schedule updated."
        } else {
            # Write-PSFMessage -Level Host -FunctionName "Import-BsgPbiDataset" -Message " Not refreshable schedule updated."
            # Write-PSFMessage -Level Verbose -FunctionName "Import-BsgPbiDataset" -Message " Schedule updated."
        }

    }catch{
        if ($Source_DatasetName){
            Write-Host
            Stop-PSFFunction -Message "Could not import schedule for dataset `"$Source_DatasetName`"." -EnableException $False -Errorrecord $_
            return
        } else{
            Write-Host
            Stop-PSFFunction -Message "Could not import schedule." -EnableException $False -Errorrecord $_
            return
        }
    }
}