Skip to main content
Skip table of contents

Adding Service Principal to Workspaces via Powershell

The below Powershell Scripts can be used to automate the process of adding the created Kada Service Principal to Workspaces for detailed lineage.

To enable the automation, we require a PowerBi User with Admin access across all Workspaces in scope.

POWERSHELL
# PowerBI Admin Login
Login-PowerBIServiceAccount

# Add user to all workspaces as Admin
$UserEmail = "abc@xyz.onmicrosoft.com"
$AccessType = "Admin"

Get-PowerBIWorkspace -Scope Organization -WarningAction Ignore |
    `Where-Object {
        $_.State -eq "Active" -and $_.Type -eq "Workspace"
    } |
    ` ForEach-Object {
        $Workspace = $_
        Add-PowerBIWorkspaceUser -Scope Organization -WarningAction Ignore `
            -Id $Workspace.Id `
            -UserPrincipalName $UserEmail `
            -AccessRight $AccessType
        Write-Host "Loaded Workspace and added user ($UserEmail) to Workspace = $($Workspace.Name), ID = $($Workspace.ID)" 
    } 

We can then add the Service Principal to all available Workspaces within the tenant using the Service Principal’s Enterprise Object ID

Note: The Object ID required here is the Enterprise App ID. Do not use the Object ID from the App registration page. It is not the correct Object ID to use.

image-20251201-041436.png
POWERSHELL
# Adding Service Principal to Workspaces
$Body = '{
    "identifier" = "{SERVICE PRINCIPAL OBJECT ID}" 
    "groupUserAccessRight" = "Member"
    "principalType" = "App"
}'

$ErrorActionPreference = "Stop"

Get-PowerBIWorkspace -Scope Organization |
    Where-Object {
        $_.State -eq "Active" -and $_.Type -eq "Workspace"
    } |
    ForEach-Object {
        $Workspace = $_
        try {
            Invoke-PowerBIRestMethod -Method POST `
                -Url "https://api.powerbi.com/v1.0/myorg/groups/$($Workspace.Id)/users" `
                -Body $Body
            
            Write-Host "Successfully added group to workspace" -ForegroundColor Green
        }
        catch {
             $errorMessage = $_.Exception.Message
              Write-Host "Error adding group to workspace $($Workspace.Name): $errorMessage" -ForegroundColor Red
        }
    }

The below Endpoint will remove the specified Service Principal from specified Workspace if required.

POWERSHELL
Invoke-PowerBIRestMethod -Method DELETE `
    -Url "https://api.powerbi.com/v1.0/myorg/groups/{WORKSPACE ID}/users/{SERVICE PRINCIPAL OBJECT ID}"
JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.