Functions/Import-BsgPbiWorkspace.ps1

<#
    .SYNOPSIS
        Import Power BI workspace from a json file.
         
    .DESCRIPTION
        Create a workspace from a definition stored in a JSON file.
 
    .PARAMETER Path_Workspace
        The path to the folder, where the workspace metadata is stored.
        The filename of the metadata must be "Workspace.json".
 
    .EXAMPLE
        # Import workspace
        Import-BsgPbiWorkspace -Path_Workspace "C:\temp\BSG PBI Administration\Backup\Workspaces\BSGroup DA - Test Workspace"
         
    .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-BsgPbiWorkspace{
    param(
        [Parameter(Mandatory=$true)][string]$Path_Workspace
    )

    try{

        Write-Host
        Write-PSFHostColor -Level Host -DefaultColor white -String "== Importing workspace..."

        # Define filename
        $FileName_WorkspaceMapping = "Mapping_Workspace.json"
        $Path_WorkspaceMapping = Join-Path -Path $Path_Workspace -ChildPath $FileName_WorkspaceMapping


        # ===
        # Check if file exists
        # =
        if ((Test-Path $Path_WorkspaceMapping) -eq $false){
            throw "File `"$FileName_WorkspaceMapping`" does not exist in path `"$Path_Workspace`". `nPlease export workspace metadata first."
        }


        # ===
        # Prepare new JSON with workspace name
        # =

        try{

            # Get workspace metadata mapping
            $WorkspaceMetadata = Get-Content -Path $Path_WorkspaceMapping | ConvertFrom-Json

            # Get workspace name
            $Target_WorkspaceName = $WorkspaceMetadata.new_name
            $Source_WorkspaceId = $WorkspaceMetadata.id

            # Define new JSON
            $Target_WorkspaceName_JSON = [PSCustomObject]@{
                name = $Target_WorkspaceName
            } | ConvertTo-Json

        } catch{
            throw "Error while preparing JSON definition with new workspace name."
        }


        # ===
        # Create new workspace (API-call)
        # =

        if ($Source_WorkspaceId -eq 'me'){
            # Personal workspace id is unchanged and already exists
            $Target_WorkspaceId = $Source_WorkspaceId
        } else{
            try{

                # Create base URLs for API requests
                $RequestUrl = "https://api.powerbi.com/v1.0/myorg/groups/"
                
                # Create workspace and get new JSON definition
                $New_WorkspaceMetadata = Invoke-PowerBIRestMethod -Url $RequestUrl -Method Post -Body $Target_WorkspaceName_JSON -ErrorAction Stop
                $New_WorkspaceMetadata = $New_WorkspaceMetadata | ConvertFrom-Json
                
                # get new workspace id
                $Target_WorkspaceId = $New_WorkspaceMetadata.id
    
            } catch{
                throw "Error after calling request URL: `"$RequestUrl`". $_ `nEnsure that the workspace does not already exist."
            }
        }
        

        # ===
        # Create mapping file (with old and new workspace IDs)
        # =

        try{

            # Add new workspace ID to Workspace Metadata
            $MappingObject = $WorkspaceMetadata
            $MappingObject | Add-Member -MemberType NoteProperty -Name "new_id" -Value "$Target_WorkspaceId"

            # Save new metadata mapping file to "xyz_Mapping.json"
            $MappingObject | ConvertTo-Json | Out-File $Path_WorkspaceMapping

        } catch{
            throw "Error when creating mapping file. $_"
        }

        Write-PSFHostColor -Level Host -DefaultColor green -String ' Workspace created.'

    } catch{
        Write-Host
        Stop-PSFFunction -Message "Could not import workspace metadata." -EnableException $False -ErrorRecord $_
    }
}