Forum Discussion

NBK52's avatar
NBK52
Helper I
1 year ago
Solved

PowerShell script to read the workspace ids/workspace name from a CSV and add them to FabricCapacity

Hi All,

 

We have list of workspaces that we need to move to newley created Fabric Capacity

 

Need a PowerShell script to read the workspace id’s/workspace name from a CSV file and add the workspace to the Fabric capacity. I could see there is a Rest API that needs to be called from PowerShell to add workspace to the Fabric capacity but not sure.

 

Could you please let us know how to do this.

  • have you installed MicrosoftPowerBIMgmt module in your PowerShell?
    If you are facing issue creating token, try below code with intercative login, make sure your user has capacity Admin and also have Admin access to all listed workapce


    # Authenticate to Power BI
    Connect-PowerBIServiceAccount


    # Define your Fabric Capacity ID
    $capacityId = "your-fabric-capacity-id"

    # Path to the CSV file
    $csvFilePath = "C:\path\to\your\workspaces.csv"

    # Read the CSV file (Ensure the CSV has a header like 'WorkspaceId' or 'WorkspaceName')
    $workspaces = Import-Csv -Path $csvFilePath

    # Loop through each workspace
    foreach ($workspace in $workspaces) {
    # Get Workspace ID (if only workspace name is provided)
    if ($workspace.WorkspaceId -eq $null -or $workspace.WorkspaceId -eq "") {
    $workspaceInfo = Get-PowerBIWorkspace -Name $workspace.WorkspaceName
    if ($workspaceInfo) {
    $workspaceId = $workspaceInfo.Id
    } else {
    Write-Host "Workspace '$($workspace.WorkspaceName)' not found!" -ForegroundColor Red
    continue
    }
    } else {
    $workspaceId = $workspace.WorkspaceId
    }

    # Add the workspace to the Fabric Capacity
    $url = "https://api.powerbi.com/v1.0/myorg/capacities/$capacityId/workspaces/$workspaceId"

    # Invoke REST API to assign the workspace
    $response = Invoke-PowerBIRestMethod -Url $url -Method Post

    # Check if the operation was successful
    if ($response) {
    Write-Host "Successfully added workspace '$workspaceId' to Fabric Capacity" -ForegroundColor Green
    } else {
    Write-Host "Failed to add workspace '$workspaceId' to Fabric Capacity" -ForegroundColor Red
    }
    }

    Write-Host "Process completed!"

9 Replies

  • arvindsingh802's avatar
    arvindsingh802
    Community Champion

    You can use below script

    # Parameters
    $csvFilePath = "C:\Path\To\Your\WorkspaceList.csv" # Update the path
    $capacityId = "your-fabric-capacity-id" # Update with your Fabric capacity ID

    # Authenticate to Power BI (use service principal or interactive login)
    $clientId = "your-client-id"
    $tenantId = "your-tenant-id"
    $clientSecret = "your-client-secret"

    $body = @{
    resource = "https://graph.microsoft.com/"
    client_id = $clientId
    client_secret = $clientSecret
    grant_type = "client_credentials"
    scope = "https://graph.microsoft.com/.default"
    }

    $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body
    $accessToken = $tokenResponse.access_token

    # Read CSV File
    $workspaces = Import-Csv -Path $csvFilePath

    # Function to get workspace ID from workspace name
    function Get-WorkspaceId {
    param ($workspaceName)
    $url = "https://api.powerbi.com/v1.0/myorg/groups"
    $headers = @{Authorization = "Bearer $accessToken"}
    $response = Invoke-RestMethod -Uri $url -Headers $headers -Method Get
    $workspace = $response.value | Where-Object { $_.name -eq $workspaceName }
    return $workspace.id
    }

    # Iterate through workspaces
    foreach ($workspace in $workspaces) {
    $workspaceId = $workspace.WorkspaceId

    # If WorkspaceId is empty, fetch it using WorkspaceName
    if (-not $workspaceId -and $workspace.WorkspaceName) {
    $workspaceId = Get-WorkspaceId -workspaceName $workspace.WorkspaceName
    }

    if ($workspaceId) {
    $assignUrl = "https://api.powerbi.com/v1.0/myorg/capacities/$capacityId/workloads/assign"
    $assignBody = @{
    groupId = $workspaceId
    } | ConvertTo-Json -Depth 1

    $assignHeaders = @{
    Authorization = "Bearer $accessToken"
    "Content-Type" = "application/json"
    }

    try {
    $response = Invoke-RestMethod -Uri $assignUrl -Headers $assignHeaders -Method Post -Body $assignBody
    Write-Output "Successfully added Workspace ID $workspaceId to Fabric capacity."
    } catch {
    Write-Output "Failed to add Workspace ID $workspaceId. Error: $_"
    }
    } else {
    Write-Output "Workspace not found: $($workspace.WorkspaceName)"
    }
    }

    • NBK52's avatar
      NBK52
      Helper I

      Thanks for providing however I am getting attached error.

      • arvindsingh802's avatar
        arvindsingh802
        Community Champion

        have you installed MicrosoftPowerBIMgmt module in your PowerShell?
        If you are facing issue creating token, try below code with intercative login, make sure your user has capacity Admin and also have Admin access to all listed workapce


        # Authenticate to Power BI
        Connect-PowerBIServiceAccount


        # Define your Fabric Capacity ID
        $capacityId = "your-fabric-capacity-id"

        # Path to the CSV file
        $csvFilePath = "C:\path\to\your\workspaces.csv"

        # Read the CSV file (Ensure the CSV has a header like 'WorkspaceId' or 'WorkspaceName')
        $workspaces = Import-Csv -Path $csvFilePath

        # Loop through each workspace
        foreach ($workspace in $workspaces) {
        # Get Workspace ID (if only workspace name is provided)
        if ($workspace.WorkspaceId -eq $null -or $workspace.WorkspaceId -eq "") {
        $workspaceInfo = Get-PowerBIWorkspace -Name $workspace.WorkspaceName
        if ($workspaceInfo) {
        $workspaceId = $workspaceInfo.Id
        } else {
        Write-Host "Workspace '$($workspace.WorkspaceName)' not found!" -ForegroundColor Red
        continue
        }
        } else {
        $workspaceId = $workspace.WorkspaceId
        }

        # Add the workspace to the Fabric Capacity
        $url = "https://api.powerbi.com/v1.0/myorg/capacities/$capacityId/workspaces/$workspaceId"

        # Invoke REST API to assign the workspace
        $response = Invoke-PowerBIRestMethod -Url $url -Method Post

        # Check if the operation was successful
        if ($response) {
        Write-Host "Successfully added workspace '$workspaceId' to Fabric Capacity" -ForegroundColor Green
        } else {
        Write-Host "Failed to add workspace '$workspaceId' to Fabric Capacity" -ForegroundColor Red
        }
        }

        Write-Host "Process completed!"

  • V-yubandi-msft's avatar
    V-yubandi-msft
    Community Support

    Hi arvindsingh802 ,

    Thank you for contacting the Microsoft Fabric Community and sharing the error details.

    Given the 403 Forbidden error message and arvindsingh802  insightful input, it seems the issue is linked to authentication or permission configurations, particularly during token creation.

     

    We appreciate arvindsingh802  assistance. To help resolve this promptly, could you please confirm the following.

    1. Are you using a Service Principal for authentication?
    2. Have you added the necessary API permissions to your Azure AD App Registration and granted admin consent? Additionally, which API endpoint are you using to assign the workspace to Fabric capacity?
    3. Does the Service Principal or user account have access to the Fabric capacity?
    4. Are the workspace IDs listed in the CSV valid and accessible?

    Thank you,

    Yugandhar.

    • NBK52's avatar
      NBK52
      Helper I

      The 4 points are successfully done but still getting the "Failed to assign workspaces. Error: The remote server returned an error: (401) Unauthorized"

  • V-yubandi-msft's avatar
    V-yubandi-msft
    Community Support

    Hi NBK52 ,

     

    We  wanted to follow up to see if the additional suggestions shared by arvindsingh802  were helpful. Please let us know if you’re still encountering any issues or need further assistance.

     

    If your issue has been resolved, we would appreciate it if you could Accept the solution to assist other community members who might face a similar challenge.

    Looking forward to your update.

    Best regards,
    Yugandhar.

  • V-yubandi-msft's avatar
    V-yubandi-msft
    Community Support

    Hello NBK52 ,

     

    we wanted to check in as we haven't heard back from you. Did our solution work for you? If you need any more help, please don't hesitate to ask. Your feedback is very important to us. We hope to hear from you soon.

     

    Thank You.

  • V-yubandi-msft's avatar
    V-yubandi-msft
    Community Support

    Hello NBK52 ,

    Could you let us know if your issue has been resolved or if you need any additional information? If the issue is resolved, please mark it as the accepted solution. This helps other members who might be facing similar issues.

    Thank You.