Tag: powershell

  • Updating PowerBI reports with PowerShell

    Updating PowerBI reports with PowerShell

    So this is probably the last PowerShell script for the moment. But this is where it gets interesting, we can now combine some of those scripts to make a quick and easy way of updating PowerBI reports with PowerShell.

    If you have the requirement where you have multiple instances of the same report across the same or different workspaces this script is for you!

    I had that requirement as part of Prism and again as things scaled up, this became a huge time saver. It also removed the potential of human error when moving parameters around, uploading to the correct workspace.

    Similar to the uploading new report script in my previous post, this one will pick up a pbix file then scan over your workspaces (based on when filters you apply). When it finds reports that again match your criteria, it will take a copy of the current parameters, update the pbix file and then load the parameters back in.

    Meaning, you have a PowerBI report uploaded to the service with your latest changes from a single source file, the parameters all remain the same as before, the script then refreshes to pull in the data based on those parameters and all good to go!

    As part of version control, I currently use a parameter to record the current version of my reports. This adds an extra benefit as I can then use this script to check if the reports are already on the expected version. Just in case the script is interrupted, we need to deploy on stages.

    I then add in the new version number as part of the script and this becomes a great way to track report versions when updating PowerBI reports with PowerShell.

    How it works?

    • Connects to Power BI Service using Connect-PowerBIServiceAccount.
    • Retrieves all Power BI workspaces using Get-PowerBIWorkspace.
    • Loops through each workspace and identifies reports whose names start with “AETHER”.
    • For each report:
    • Retrieves the dataset parameters.
    • Updates the first parameter’s value to a specified version if it doesn’t already match.
    • Overwrites the report in the workspace using a specified PBIX file ($FilePath).
    • Takes over the dataset to ensure permissions are set correctly.
    • Updates the dataset parameters.
    • Triggers a dataset refresh.

    Key things you can change

    • $DeployVer: The new deployment version to update the first parameter to (e.g., “2025Q1”).
    • $FilePath: The path to the PBIX file used for updating reports.
    • Parameter 0 is assumed to represent a version parameter (e.g., “2025Q1”)

    https://github.com/AetherAdv/powerbi_powershell_updatereports/upload/main

    # Connect to Power BI Service Account
    Connect-PowerBIServiceAccount
    
    # Set the deployment version to be used for updating parameters
    $DeployVer = "2025Q1"
    
    # Define the path to the PBIX file to be used for report updates
    $FilePath = "C:\Temp\myreport.pbix"
    
    # Define the conflict action for updating reports (e.g., Create or Overwrite existing reports)
    $Conflict = "CreateOrOverwrite"
    
    # Retrieve all Power BI workspaces
    $workspaces = Get-PowerBIWorkspace -All
    
    # Loop through each workspace
    foreach ($workspace in $workspaces) {
    
        # Get all reports in the current workspace with names starting with "AETHER"
        $Reportlist = Get-PowerBIReport -WorkspaceId $workspace.Id | Where-Object { $_.Name -like 'AETHER*' }
    
        # Check if any reports were found in the workspace
        if ($Reportlist) {
            Write-Host "Workspace: $($workspace.Name)" # Log the workspace name
    
            # Loop through each report in the report list
            foreach ($Report in $Reportlist) {
                Write-Host "  Report: $($Report.Name)" # Log the report name
    
                $JsonString = $null # Initialize JSON string variable
    
                # Retrieve the parameters of the dataset associated with the report
                $ParametersJsonString = Invoke-PowerBIRestMethod -Url "https://api.powerbi.com/v1.0/myorg/groups/$($workspace.Id)/datasets/$($Report.DatasetId)/parameters" -Method Get
                $Parameters = (ConvertFrom-Json $ParametersJsonString).value # Convert JSON response to PowerShell object
    
                # Initialize an empty array to hold parameter updates
                $UpdateParameterList = @()
    
                # Loop through each parameter and prepare the update list
                foreach ($Parameter in $Parameters) {
                    $UpdateParameterList += @{ "name" = $Parameter.name; "newValue" = $Parameter.currentValue }
                }
    
                # Check if there are any parameters to update
                if ($UpdateParameterList.Count -gt 0) {
                    # Get the current value of the first parameter
                    $currentparam = $UpdateParameterList[0].newValue
    
                    Write-Host "    Current Parameter 0 Value: $currentparam" # Log the current parameter value
    
                    # Check if the current parameter value matches the deployment version
                    if ($currentparam -ne $DeployVer) {
                        Write-Host "Version does not match. Updating..." # Log the update action
    
                        # Update the first parameter to the new deployment version
                        $UpdateParameterList[0].newValue = $DeployVer
                    }
                    else {
                        Write-Host "Version already matches. Skipping update." # Log if no update is needed
                    }
    
                    # Prepare the JSON payload for updating parameters
                    $JsonBase = @{ "updateDetails" = $UpdateParameterList }
                    $JsonString = $JsonBase | ConvertTo-Json
    
                    # Define the report name
                    $ReportName = $Report.Name
    
                    # Update the existing report in the workspace
                    New-PowerBIReport -Path $FilePath -Name $ReportName -WorkspaceId $workspace.Id -ConflictAction $Conflict
    
                    # Take over the dataset to ensure permissions are set correctly
                    Invoke-PowerBIRestMethod -Url "https://api.powerbi.com/v1.0/myorg/groups/$($workspace.Id)/datasets/$($Report.DatasetId)/Default.TakeOver" -Method Post
    
                    # Update the parameters of the dataset
                    Invoke-PowerBIRestMethod -Url "https://api.powerbi.com/v1.0/myorg/groups/$($workspace.Id)/datasets/$($Report.DatasetId)/Default.UpdateParameters" -Method Post -Body $JsonString
    
                    # Pause for 5 seconds to avoid API rate limits
                    Start-Sleep -Seconds 5
    
                    # Trigger a dataset refresh
                    Invoke-PowerBIRestMethod -Url "https://api.powerbi.com/v1.0/myorg/groups/$($workspace.Id)/datasets/$($Report.DatasetId)/refreshes" -Method Post
                    Write-Host "Refresh started." # Log the refresh action
                }
                else {
                    Write-Host "No parameters found for this dataset." # Log if no parameters are found
                }
            }
        } else {
            Write-Host "No reports found in workspace: $($workspace.Name)" # Log if no reports are found in the workspace
        }
    }
    
    # Log the completion of the script
    Write-Host "Script completed."
  • Add permissions to PowerBI Deployment pipelines

    Add permissions to PowerBI Deployment pipelines

    A relatively simple post today, but just this past week a customer came to me with an issue where they had accidentally removed permissions from one of their primary PowerBI deployment pipelines. They still had the PowerBI service admin permissions but could no longer see the pipelines via the PowerBI site.

    Naturally, as per recent blogs. I wrote a PowerShell script that links into the PowerBI Rest API that can then add permissions to PowerBI Deployment pipelines!

    Hopefully if you find yourself in a similar situation this script may quickly help you out

    I’ve broken this script down into three parts, get a list of all pipelines so we can find the specific IDs, check existing pipeline users and then add new users.

    • Firstly we connect to the PowerBI service (this is going to be needed for all 3 parts)
    • We then define the API endpoint we want to use to target all pipelines. $apiUrlPipelines = “admin/pipelines” . Note we use the admin endpoint otherwise the script will only target what your user account specifically has access to
    • Invoke the PowerBI Rest method to pull back information on all pipelines – we are mainly interested in the pipeline IDs
    • Using our existing connection to the PowerBI service
    • We then define the API endpoint of the specific pipeline using the Pipeline ID as one of the variables
    • Finally invoke the PowerBI Rest method, which will pull back the existing users
    • Again using the existing connection
    • And also the same API endpoint we used to check for existing users
    • Using the email address / upn of the user to add in a variable we then load the body to POST to the API endpoint. In this script I have set the access right as Admin and the principal type as User
    • Invoke the PowerBI Rest method, to then add the User account

    https://github.com/AetherAdv/powerbi_powershell_addpipelinepermissions

    Connect-PowerBIServiceAccount
    
    
    # Get list of pipelines (optional)
    $apiUrlPipelines = "admin/pipelines"
    $pipelineList = Invoke-PowerBIRestMethod -Url $apiUrlPipelines -Method Get
    
    #---------------------------------
    
    $pipelineId = "####"
    $userEmail = "[email protected]"
    
    # Get users assigned to a pipeline
    $apiUrlUsers = "admin/pipelines/$pipelineId/users"
    $pipelineUsers = Invoke-PowerBIRestMethod -Url $apiUrlUsers -Method Get
    $pipelineUsers | ConvertTo-Json -Depth 2
    
    
    # Add a user as Admin
    $body = @{
        identifier = $userEmail
        accessRight = "Admin"
        principalType = "User"
    } | ConvertTo-Json -Depth 3
    
    Invoke-PowerBIRestMethod -Url $apiUrlUsers -Method Post -Body $body -ContentType "application/json"
    
  • Uploading new reports with PowerShell

    Uploading new reports with PowerShell

    At this point you may be starting to wonder how many PowerShell scripts I have for working with PowerBI, turns out quite a few! Uploading new reports with PowerShell is the latest one!

    As Prism grew I was looking at more workspaces and more reports, and so I turned to what I knew best at the time, PowerShell. Whilst going into PBI desktop, ensuring the data was loaded up then publishing to the PowerBI service doesn’t take a huge amount of time individually, but when building a product I needed much greater flexibility.

    So what this latest script does is solve that exact problem.

    The PBIX files I have are all loaded into source control but have a copy ready that is synced via VsCode. This script will pick up that file and upload it to the PowerBI workspace as required. (Even creating the PowerBI workspace and adding permissions at the same time if needed!)

    In my case and something you may be interested in as well, I then combined this script with a couple of the others I have already posted about. Adding parameters and setting refresh times. At this point you can automate the whole thing end to end!

    How does it work?

    This script whilst looks simple, will do quite a few things!

    Firstly, you need to provide a name for your workspace and a name for your report. These are going to be what the script uses, regardless of what your PBIX file is named already.

    If using this part of the code, you will also need to supply your capacity ID. This is so the workspace can then link up with your premium / embedded / fabric etc capacity. Note this will require you to have a level of admin permissions in your organisation if you want to do this automated.

    Once it has set those, it will add a new user (usually best to have more than just yourself as an admin on these things). In this example ive added a user, you can add groups , distribution lists all sorts. Prism for example, we have support teams as group who get applied to new workspaces.

    Lastly it will upload the PBIX file you specified, name it how you wanted all ready to go!

    The Script

    Connects to the PowerBI service Account

    Uses the parameters you have set to:

    Create a PowerBI workspace

    Add it to the specified capacity

    Adds a new admin user

    Add the PowerBI report

    Like I say, combine this with the other PowerShell scripts I have posted about uploading new reports with PowerShell will then go even further! Especially if you are using PowerBI as part of a product or simply dealing with many workspaces and reports.

    https://github.com/AetherAdv/powerbi_powershell_addnew

    # Ensure Power BI module is installed
    Import-Module MicrosoftPowerBIMgmt
    
    # Connect to Power BI (if not already connected)
    Connect-PowerBIServiceAccount
    
    # Define conflict action
    $Conflict = "CreateOrOverwrite"
    
    # Define Capacity ID
    $CapacityId = "00000000-0000-0000-0000-000000000000"  # Replace with your capacity ID
    
    # Define workspace details
    $WorkspaceName = "AETHER - MyNewWorkspace"
    
    # Define report details
    $ReportName = "AETHER - MyReport"
    
    # Define PBIX file path
    $DeployPath = "C:\Temp\myreport.pbix"
    
    # Create the workspace
    $Workspace = New-PowerBIWorkspace -Name $WorkspaceName
    
    # Wait a few seconds for workspace creation - just incase it needs time to be accessible
    Start-Sleep -Seconds 5
    
    # Assign the workspace to a Power BI Premium capacity - Not this will require some additional licence and access considerations to do with commands!
    Set-PowerBIWorkspace -Id $Workspace.Id -CapacityId $CapacityId -Scope Organization
    
    # Add a user as an admin
    Add-PowerBIWorkspaceUser -Id $Workspace.Id -UserPrincipalName "[email protected]" -AccessRight Admin
    
    # Publish the Power BI report
    New-PowerBIReport -Path $DeployPath -Name $ReportName -WorkspaceId $Workspace.Id -ConflictAction $Conflict