Functions/Import-BsgPbiWorkspaceUsers.ps1

<#
    .SYNOPSIS
        Import Power BI workspace users from a json file.
         
    .DESCRIPTION
        Create all workspace user permissions from a definition stored in a JSON file.
 
    .PARAMETER Path_Workspace
        The path to the folder, where the workspace users is stored.
        The filename of the JSON file must be "WorkspaceUsers.json".
 
    .PARAMETER Target_WorkspaceId
        The id of the workspace where the users should be imported.
        You can find it in the Power BI workspace URL.
 
    .EXAMPLE
        # Import workspace users
        Import-BsgPbiWorkspaceUsers -Path_Workspace "C:\temp\BSG PBI Administration\Backup\Workspaces\BSGroup DA - Test Workspace" -Target_WorkspaceId 40252f5a-655a-4f2c-a86f-34d8bc64423a
         
    .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-BsgPbiWorkspaceUsers{

    param(
        [Parameter(Mandatory=$true)][string]$Path_Workspace,
        [Parameter(Mandatory=$true)][string]$Target_WorkspaceId
    )

    try{

        Write-Host
        Write-PSFHostColor -Level Host -DefaultColor white -String "== Importing workspace users..."
    
        # Define 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
        }
        $RequestUrl = $Target_WorkspaceUrl + "/users"

        $FileName_WorkspaceUsers = "WorkspaceUsers.json"
        $Path_WorkspaceUsers = Join-Path -Path $Path_Workspace -ChildPath $FileName_WorkspaceUsers
    
    
        # ===
        # Check if user file exists
        # =

        if ((Test-Path $Path_WorkspaceUsers) -eq $false){
            throw "File `"$FileName_WorkspaceUsers`" does not exist in path `"$Path_Workspace`". `nPlease export workspace metadata first."
        }

    
        # ===
        # Get user file
        # =

        try{

            # Get file
            $Source_WorkspaceUsers = Get-Content -Path $Path_WorkspaceUsers | ConvertFrom-Json

            # Get number of users
            $Source_TotalNumOfUsers = $Source_WorkspaceUsers.value.count

        } catch{
            throw "Error while getting workspace user JSON definition. `n$_"
        }
        

        # ===
        # Get current users (API-Request)
        # =

        try{
            $Target_CurrentUsers = Invoke-PowerBIRestMethod -Url $RequestUrl -Method Get -ErrorAction Stop
            $Target_CurrentUsers = $Target_CurrentUsers | ConvertFrom-Json
            $Target_CurrentUsers = $Target_CurrentUsers.value
            
        } catch{
            throw "Error trying to get current users when calling request URL: `"$RequestUrl`". `n$_"
        }

    
        # ===
        # Create new users (API-Request)
        # =

        try{

            $Target_NumOfNewUsers = 0;
            $Target_NumOfMissingUsers = 0;

            foreach ($user in $Source_WorkspaceUsers.value) {

                # Get user data
                $RequestBody = $user | ConvertTo-Json;
                $UserName = $user.displayName

                # Check if user exists
                $UserExists = $Target_CurrentUsers.identifier -contains $user.identifier

                # Only add new users
                if ($UserExists -eq $false){

                    # Create workspace and get new JSON definition
                    $Response = Invoke-PowerBIRestMethod -Url $RequestUrl -Method Post -Body $RequestBody -ErrorAction SilentlyContinue
                    if ($null -ne $Response){
                        $Target_NumOfNewUsers += 1;
                    } else{
                        $Target_NumOfMissingUsers += 1;
                    }

                }

            }

            $Target_WorkspaceUsers = Invoke-PowerBIRestMethod -Url $RequestUrl -Method Get -ErrorAction Stop | ConvertFrom-Json
            $Target_TotalNumOfUsers = $Target_WorkspaceUsers.value.count
            #$Target_NumOfMissingUsers = $Source_TotalNumOfUsers - $Target_TotalNumOfUsers

        } catch{
            throw "Error after calling request URL: `"$RequestUrl`". `nUser may already exist: $UserName `n$_"
        }
    
        If ($Target_NumOfNewUsers -eq 0){
            Write-Host
            Write-PSFHostColor -Level Host -DefaultColor gray -String " No user created. Total workspace users: <c='white'>$Target_TotalNumOfUsers</c>.";
        } elseif ($Target_NumOfNewUsers -eq 1){
            Write-Host
            Write-PSFHostColor -Level Host -DefaultColor gray -String " <c='green'>$Target_NumOfNewUsers</c> user created. Total workspace users: <c='white'>$Target_TotalNumOfUsers</c>."
        } else {
            Write-Host
            Write-PSFHostColor -Level Host -DefaultColor gray -String " <c='green'>$Target_NumOfNewUsers</c> users created. Total workspace users: <c='white'>$Target_TotalNumOfUsers</c>."
        }

        if ($Target_NumOfMissingUsers -gt 1){
            Write-Host
            Write-Warning "$Target_NumOfMissingUsers users could not be restored."
            Write-Host
            Write-PSFHostColor -Level Host -DefaultColor white -String " Please ensure, that the users belong to the right domain and tenant."
        } elseif ($Target_NumOfMissingUsers -eq 1){
            Write-Host
            Write-Warning "$Target_NumOfMissingUsers user could not be restored."
            Write-Host
            Write-PSFHostColor -Level Host -DefaultColor white -String " Please ensure, that the user belongs to the right domain and tenant."
        }

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

}