Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Register now to learn Fabric in free live sessions led by the best Microsoft experts. From Apr 16 to May 9, in English and Spanish.

Reply
kustbilla
Frequent Visitor

500 Internal Server Error encountered when importing PBIX file using PowerShell script

I created below PowerShell script to import PBIX file to workspace:

 

$LF = "`r`n"
$boundary = "----------abcdefghijklmn"
$uri = "https://api.powerbi.cn/v1.0/collections/stanley-test/workspaces/10b69fc3-46fa-464b-9483-41b77b426bb8..."
$CODEPAGE = "iso-8859-1"

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "AppKey <accesskey>
$FileContent = [System.IO.File]::ReadAllBytes("D:\temp\RetailAnalysisSamplePBIX.pbix");
$enc = [System.Text.Encoding]::GetEncoding($CODEPAGE)
$fileEnc = $enc.GetString($FileContent)

$body = ("--$boundary$LF",
            "Content-Disposition: form-data; name=`"filename`"; filename=`"RetailAnalysisSamplePBIX.pbix`"$LF",
            "Content-Type: application/octet–stream$LF",
            $fileEnc,
            $LF,
            "--$boundary--",
            $LF) -join $LF;

Invoke-RestMethod -ContentType "multipart/form-data" -Method POST -Uri $uri -Body $body -Headers $headers

 

But when I ran this script it failed with the error "HTTP/1.1 500 Internal Server Error", I'm sure the URL/access key/pbix file path are right but it doesn't work.

 

Can someone help to figure it out? Any answer is greatly appreciated.

 

P.S. PowerShell response:

Invoke-RestMethod : {"Message":""}
At C:\Users\weihuan\Desktop\stanleytest.ps1:20 char:1
+ Invoke-RestMethod -ContentType "multipart/form-data" -Method POST -Ur ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (Method: POST, R...rt/form-data
}:HttpRequestMessage) [Invoke-RestMethod], HttpResponseException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

2 REPLIES 2
Eric_Zhang
Employee
Employee

@kustbilla

I know how to call the import api to upload a pbix file in C#, however I don't have much expertise on PowerShell. Please reference below C# code and modify the powershell script accordingly

 

using System;
using System.Net;
using System.IO;  

namespace PBIGettingStarted
{
    class Program
    {
        //Access key for app token
        private static string accessKey = "myaccesskey";

        //Power BI app token values
        private static string workspaceCollectionName = "myworkspace";
        private static string workspaceId = "myworkspaceid";

        private static string pbixFileName = "AdventureWorksdddd.pbix";

        static void Main(string[] args)
        {
            //Imports uri
            var uri = String.Format
                ("https://api.powerbi.com/v1.0/collections/{0}/workspaces/{1}/imports?datasetDisplayName=SampleImport",
                workspaceCollectionName, workspaceId);

            //PBIX file to import
            DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            string fileName = @"C:\test\mytest.pbix";
 
            //Create web request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            //Import Request format:
            // Header:
            //  Content - Type: multipart / form - data; ----------BOUNDARY
            //  Authorization: AppToken

            // Body:
            //  ----------BOUNDARY
            //  Content - Disposition: form - data; filename = "{pbix file}.pbix"
            //  Content - Type: application / octet – stream

            //Define POST
            request.Method = "POST";
            request.UseDefaultCredentials = true;

            //Header
            // Boundary
            string boundary = "----------BOUNDARY";
            byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            // Content - Type
            request.ContentType = "multipart/form-data; boundary=" + boundary;

            // Authorization - Use AppToken jwt for Authorization header
            request.Headers.Add("Authorization", String.Format("AppKey {0}", accessKey));

            //Body
            string bodyTemplate = "Content-Disposition: form-data; filename=\"{0}\"\r\nContent-Type: application / octet - stream\r\n\r\n";
            string body = string.Format(bodyTemplate, fileName);
            byte[] bodyBytes = System.Text.Encoding.UTF8.GetBytes(body);

            //Get request stream 
            using (Stream rs = request.GetRequestStream())
            {
                rs.Write(boundaryBytes, 0, boundaryBytes.Length);
                rs.Write(bodyBytes, 0, bodyBytes.Length);

                using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    byte[] buffer = new byte[4096];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        rs.Write(buffer, 0, bytesRead);
                    }
                }

                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                rs.Write(trailer, 0, trailer.Length);
            }

            //Get response
            using (HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse)
            {
                //If Import succeeds, StatusCode = Accepted 
                var responseStatusCode = response.StatusCode.ToString();
            }
        }
    }
     

    }

@Eric_Zhang

Thanks Eric for your kind helpSmiley Happy

Helpful resources

Announcements
Microsoft Fabric Learn Together

Microsoft Fabric Learn Together

Covering the world! 9:00-10:30 AM Sydney, 4:00-5:30 PM CET (Paris/Berlin), 7:00-8:30 PM Mexico City

PBI_APRIL_CAROUSEL1

Power BI Monthly Update - April 2024

Check out the April 2024 Power BI update to learn about new features.

April Fabric Community Update

Fabric Community Update - April 2024

Find out what's new and trending in the Fabric Community.