Sub topic 12
Publishing from a Script: PowerShell and the REST API
This chapter shows how to publish a .pbix file without opening Power BI Desktop. It assumes you have already published a report by hand and understand workspaces, workspace roles, and the report and semantic model pair that publishing creates. You should also be comfortable running commands in a terminal.
Why script the publish
Publishing from Desktop works well for one report. It becomes tedious when you:
- publish the same report to development, test, and production workspaces,
- run publishing from a build or release pipeline,
- republish many reports after a change,
- need a repeatable, reviewable record of what was published and where.
Two tools cover this. The MicrosoftPowerBIMgmt PowerShell module wraps the common operations in cmdlets. The Power BI REST API is the underlying HTTP interface, which you can call from any language or from curl.
Both do the same thing as Desktop's Publish button: they upload the .pbix file as an import. The service then creates or updates the report and the semantic model in the target workspace.
Requirements before you run anything
A script has the same permission needs as a person. The account or service principal that runs it must:
- have the Admin, Member, or Contributor role on the target workspace (Viewer cannot publish),
- hold a license, or sit in a capacity, that allows publishing to that workspace,
- be allowed by your tenant settings to use the Power BI APIs.
If a script fails with an authorization error, check the workspace role first. Most failures come from a missing role, not from a bug in the script.
Publishing with PowerShell
Install the module and sign in
The first example installs the module for your user, signs in, and looks up a workspace. Run it first to confirm that you can see the workspace you intend to publish to.
Install-Module -Name MicrosoftPowerBIMgmt -Scope CurrentUser
Connect-PowerBIServiceAccount
Get-PowerBIWorkspace -Name 'Sales Analytics'Connect-PowerBIServiceAccount opens a sign-in window and stores a token for the session. Get-PowerBIWorkspace returns workspaces you can access. If it returns nothing, you either misspelled the name or you have no role in that workspace. Publishing would fail in the same way.
Upload the file
Once the lookup works, upload the file with New-PowerBIReport.
Connect-PowerBIServiceAccount
$ws = Get-PowerBIWorkspace -Name 'Sales Analytics'
New-PowerBIReport -Path '.\Sales.pbix' -Name 'Sales' -Workspace $ws -ConflictAction CreateOrOverwriteThe parameters work like this:
| Parameter | Meaning |
|---|---|
| `-Path` | Location of the local `.pbix` file. |
| `-Name` | Display name for the report and its semantic model in the workspace. |
| `-Workspace` | The workspace object returned by `Get-PowerBIWorkspace`. |
| `-ConflictAction` | What to do if an item with this name already exists. |
Choose a conflict action
-ConflictAction decides what happens when the workspace already holds an item with the same name. The accepted values are:
Ignore: do nothing special. If the name exists, the import may fail or create a duplicate, depending on the item type.Abort: stop and report an error if the name exists.Overwrite: replace the existing item.CreateOrOverwrite: create the item if it is new, or replace it if it exists.
Use CreateOrOverwrite for repeatable pipelines, because the same script works on the first run and every later run. Use Abort when a name collision would mean something is wrong, such as a first-time deployment to a workspace that should be empty.
Use a variable for the workspace name
Hard-coded names make a script hard to reuse. Parameterize it, and fail early if the workspace is missing.
param(
[Parameter(Mandatory = $true)] [string] $WorkspaceName,
[Parameter(Mandatory = $true)] [string] $PbixPath,
[string] $ReportName = [System.IO.Path]::GetFileNameWithoutExtension($PbixPath)
)
Connect-PowerBIServiceAccount | Out-Null
$ws = Get-PowerBIWorkspace -Name $WorkspaceName
if (-not $ws) {
throw "Workspace '$WorkspaceName' was not found or you have no access to it."
}
$report = New-PowerBIReport -Path $PbixPath -Name $ReportName -Workspace $ws -ConflictAction CreateOrOverwrite
Write-Output "Published '$($report.Name)' with report ID $($report.Id)"Save it as Publish-Report.ps1 and call it like this:
.\Publish-Report.ps1 -WorkspaceName 'Sales Analytics' -PbixPath '.\Sales.pbix'The throw line matters. Without it, a null workspace passes into New-PowerBIReport, and the resulting error message is harder to read.
Publishing with the REST API
The Imports operation
The REST API publishes through the Imports operation. You send a POST request to a workspace-specific URL, with the file as multipart form data. In the API, a workspace is called a group, and its ID is the group ID.
curl -X POST "https://api.powerbi.com/v1.0/myorg/groups/$GROUP_ID/imports?datasetDisplayName=Sales&nameConflict=CreateOrOverwrite" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-F "[email protected]"The pieces of this request:
groups/$GROUP_IDtargets a specific workspace. Withoutgroups/..., the import goes to the caller's personal "My workspace".datasetDisplayNamesets the name of the imported item. It is required.nameConflictcontrols duplicates. For.pbixfiles the useful values areAbort,Overwrite, andCreateOrOverwrite.-F "[email protected]"makescurlsend the file asmultipart/form-data.Authorization: Bearer ...carries a Microsoft Entra ID access token.
The workspace ID is a GUID. You can copy it from the workspace URL in the service, or retrieve it with Get-PowerBIWorkspace, which exposes an Id property.
Getting an access token
The request needs a valid token for the Power BI resource. There are two common ways to get one.
- Signed-in user. For testing,
Get-PowerBIAccessToken -AsStringreturns the token of your current PowerShell session, prefixed withBearer. - Service principal. For automation, register an app in Microsoft Entra ID, grant it access to the workspace as Admin, Member, or Contributor, and request a token with the client credentials flow. Your tenant admin must also allow service principals to use Power BI APIs.
Handling the response
A successful POST returns a response containing an import ID, and the import runs asynchronously. A small file may finish in seconds. A large one can take longer. To confirm completion, poll the import with GET .../groups/{groupId}/imports/{importId} until importState is Succeeded. If it is Failed, the response has details.
The following sketch shows the same flow in PowerShell using Invoke-PowerBIRestMethod, which reuses your signed-in session and avoids token handling.
Connect-PowerBIServiceAccount
$ws = Get-PowerBIWorkspace -Name 'Sales Analytics'
$url = "groups/$($ws.Id)/imports?datasetDisplayName=Sales&nameConflict=CreateOrOverwrite"
$import = Invoke-PowerBIRestMethod -Method Post -Url $url -Body (Get-Content '.\Sales.pbix' -Raw) | ConvertFrom-JsonReading a binary file with -Raw into a string is unreliable, and multipart bodies are awkward in this cmdlet. For uploads, prefer New-PowerBIReport or curl. Use Invoke-PowerBIRestMethod for the follow-up calls, such as polling the import:
Invoke-PowerBIRestMethod -Method Get -Url "groups/$($ws.Id)/imports/$ImportId" | ConvertFrom-JsonHere $ImportId holds the ID from the upload response.
Choosing between the two
| Factor | PowerShell module | REST API with `curl` or code |
|---|---|---|
| Setup | Install one module | Obtain tokens yourself |
| Upload handling | Done for you | You build the multipart request |
| Polling the import | Cmdlet waits for the result | You poll manually |
| Works from any language | No, PowerShell only | Yes |
| Best fit | Admin scripts, Windows pipelines | Cross-platform pipelines, other languages |
Use the module when your team already works in PowerShell. Use the REST API when your pipeline runs in another language, or when you need operations the module does not wrap.
What a script does not do
Publishing creates or updates the report and the semantic model. It does not finish the setup that the earlier chapters covered. After the first publish to a new workspace, you still need to:
- set data source credentials, and configure a gateway if the data is on premises,
- configure scheduled refresh,
- verify that the report opens and shows data,
- share the report or grant access to the right people.
Some of these steps can also be scripted with other REST operations, but the first time through, do them by hand and check the result. A scripted publish into a workspace you have never checked often succeeds and still produces a report that shows a refresh error.
Common errors
- 401 Unauthorized. The token is missing, expired, or issued for the wrong resource. Sign in again or request a new token.
- 403 Forbidden. The account is signed in but has no suitable role on the workspace, or a tenant setting blocks API access.
- 404 Not Found. The group ID is wrong, or the account cannot see the workspace.
- Name conflict failure. You used
Abortor the default, and an item with that name exists. Switch toCreateOrOverwriteif replacing is what you want. - Import stays in progress or fails. Poll the import and read the error. Very large files, or a file saved by a newer Desktop version than the service supports, are frequent causes.
- Report published to "My workspace". The URL omitted
groups/{id}, or the PowerShell call omitted-Workspace.
Exercise
You run New-PowerBIReport -Path '.\Sales.pbix' -Name 'Sales' -Workspace $ws -ConflictAction CreateOrOverwrite for the second time against the same workspace. What happens, and which role must your account have?
Show answer
The first run created a report and semantic model named Sales. The second run replaces them with the contents of the file instead of failing or creating duplicates, because CreateOrOverwrite creates the item when it is new and overwrites it when it exists. Your account needs the Admin, Member, or Contributor role on the workspace. Viewer is not enough.
Exercise
A colleague's curl command returns success, but the report appears in their "My workspace" instead of the team workspace. Which part of the request is most likely wrong, and how do you fix it?
Show answer
The URL probably lacks the groups/{groupId} segment, so the import targets the personal workspace. Use https://api.powerbi.com/v1.0/myorg/groups/$GROUP_ID/imports?... with the correct workspace ID.
Exercise
Write the extra check you would add to a script after uploading with the REST API, to know whether the import finished.
Show answer
Take the import ID from the upload response and poll GET https://api.powerbi.com/v1.0/myorg/groups/$GROUP_ID/imports/$IMPORT_ID until the importState field is Succeeded. If it becomes Failed, stop and read the error details in the response.