Invoke-WebRequest : You must write ContentLength bytes to the request stream before calling [Begin]GetResponse - azure

I need to import some files to Power BI using API and powershell
First I create a temporary upload with: groups/group_id/imports/createTemporaryUploadLocation
Then I push my file to the URL
Invoke-RestMethod -Method PUT -Uri \"${url}\" -Header #{ \'x-ms-blob-type\' = \'BlockBlob\'; \'Content-Length\' = $len } -InFile '$myFile' -TimeoutSec 3600
Finally, I try to import that URL to PowerBi using:
Invoke-WebRequest -Method POST -Uri "https://api.powerbi.com/v1.0/myorg/groups/group_id/imports?datasetDisplayName=$myFile&nameConflict=O..." -Header #{Authorization = '$Token'; 'Content-Length' = $len} -Body '{ "fileUrl"= "url"}' | ConvertTo-Json -Depth 5
I am getting the following error:
Invoke-WebRequest : You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
What am I doing wrong?
I added the content-length because I was getting this error:
{"error":{"code":"InvalidFileSizeError","pbi.error":{"code":"InvalidFileSizeError","parameters":{"FileSize":"1839362"},"details":[],"exceptionCulprit":1}}}
According to this page, we had to add content length in request https://community.powerbi.com/t5/Developer/Post-in-Group-API-using-Nodejs/m-p/1054892

Related

Why do I get "Request Entity Too Large" When Using the ZipDeploy API Azure?

I have a ASP.NET zip that I'm attempting to upload to an ASE slot using the zipdeploy API, and for one slot it's erroring out resulting in a "Request entity too large" error.
Here's the code I'm using:
$url = "https://" + $slot + "/api/zipdeploy?isAsync=true"
Invoke-WebRequest -Uri $url -Headers #{Authorization = ("Basic {0}" -f $authInfo)} -Method POST -UseBasicParsing -InFile $zip -ContentType "multipart/form-data"
If I use a relatively small zip it'll work, but if I use the zip I want which is 100MB+, it'll fail.

Powershell invoke-restmethod variable in url

I am new to powershell, and I am trying to create a simple script that will allow me to turn on several Azure VMs using the invoke-restmethod.
My code works when instead of using a variable I directly write the VM name into the url, but I want to use a variable, since eventually this must work for more than one VM.
Relevant part of code:
$body = #{
"$virtualMachines" = "VM1"
} | ConvertTo=Json
$url= "https://management.azure.com/subscriptions/mySubscriptionId/resourceGroups/myResourceGroupName/providers/Microsoft.DevTestLab/labs/myLabName/virtualmachines/" + $virtualMachines + "/start?api-version=2018-09-15"
$response = Invoke-RestMethod -uri $url -Method 'POST' -Headers $headers -Body $body
$response | ConvertTo-Json
If you had a number of VMs, you could put them all into a PowerShell variable like this, an array of strings.
$VMs = "myVm1", "myVm2", "myVm3"
PowerShell has a number of flow control statements, the one you want to use is ForEach, which will step through an array one at a time. We just modify the way you're setting up the URL to be friendlier and easier to read and this should work just fine.
$baseUrl = "https://management.azure.com/subscriptions/mySubscriptionId/resourceGroups/myResourceGroupName/providers/Microsoft.DevTestLab/labs/myLabName/virtualmachines/"
ForEach ($vm in $VMs){
$url = $baseurl + $vm + "/start?api-version=2018-09-15"
Write-host "About to start [$Vm]"
$response = Invoke-RestMethod -uri $url -Method 'POST' -Headers $headers
$response | ConvertTo-Json
}
I checked the API documentation for the start? REST API endpoint, and it doesn't look like you need the -Body parameter for this endpoint.

Update defaultBranch of build definition via Azure DevOps API

I need to update the defaultBranch of build definition via Azure API.
The is the documentation for PUT request:
https://learn.microsoft.com/en-us/rest/api/azure/devops/build/definitions/update?view=azure-devops-rest-5.1
The problem is that I don't know the minimum list pf params I need to send in order to create a working request.
I tried to export the actual request from the browser and modify only this field - status code is 200 but nothing was changed. I don't want to pass all filed I just want to modify the defaultBranch.
In the link you provided you have Request Body section, you can see there what you need to pass. I like to get the definition first (with Get API), change what I want, and then perform the update.
In PowerShell:
$pat = "YOUR-PAT"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,"$pat")))
$headers = #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$url = "https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=5.1"
$build = Invoke-RestMethod -Uri $url -Method Get -ContentType application/json -Headers $headers
$newDefaultBranch = "test-branch"
$build.repository.defaultBranch = $newDefaultBranch
$json = $build | ConvertTo-Json -Depth 10
$response = Invoke-RestMethod -Uri $url -Method Put -ContentType application/json -Headers $headers -Body $json

Erorr exporting Azure sql database to blob storage with powershell

I'm trying to use Azure management API to export a SQL database to a bacpac file in a blob storage. The process seems fairly simple: obtain a token, and then:
$sqlAzureBackupHeaders = #{
Authorization = "Bearer $accessToken"
}
$sqlAzureBackupParams = #{
storageKey = "<key-goes-here>",
storageUri = "http://mystorageacct.blob.core.windows.net/my-blob-container/export-name.bacpac",
storageKeyType = "StorageAccessKey",
administratorLogin = "<sql-user>",
administratorLoginPassword = "<sql-password>",
authenticationType = "SQL"
}
$sqlAzureApiUri = "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Sql/servers/<server-name>/databases/<database-name>/export?api-version=2014-04-01"
Invoke-RestMethod -Uri $sqlAzureApiUri -Method Post -Headers $sqlAzureBackupHeaders -Body $sqlAzureBackupParams
This results in an error:
Invoke-RestMethod : Receivera:InternalServiceFaultThe server was unable to process the request due to an internal error. For more
information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the
<serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing
as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.
At D:\Users\protec-admin\Desktop\run-backups.ps1:140 char:1
+ Invoke-RestMethod -uri $sqlAzureApiUri -Method Post -Headers $sqlAzur ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I tried using Invoke-WebRequest and converting body to json string - with the same result.
When I try the same call using Postman, it works fine, so there's something with making the call from powershell that's not working correctly.
How can I get this working from powershell?
According to my test, the rest API just accept the json body. Please use ConvertTo-Json to convert the body to json.
For example
$headers=#{"Authorization" = "Bearer "+$token}
$body=#{
"storageKeyType"= "StorageAccessKey";
"storageKey"= "<your storage account access key>";
"storageUri"= "https://blobstorage0516.blob.core.windows.net/sample/testbacpac2.bacpac";
"administratorLogin"= "<SQL admin>";
"administratorLoginPassword"= "<SQL admin passsword>";
"authenticationType"= "SQL"
}|ConvertTo-Json
$sqlAzureApiUri = "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Sql/servers/<server-name>/databases/<database-name>/export?api-version=2014-04-01"
Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $body -UseBasicParsing -ContentType "application/json"

Powershell - How to parse the response

All, I am new to powershell and trying with a simple powershell script which invokes a REST API and get the value.
The scenario is, Using powershell will trigger a POST request and get the response value and using that value as a parameter in another GET API request.
POST :
$Params = #{"id"=38}
$headers = #{
Authorization="Bearer XXXXXX"
$getrunid=Invoke-RestMethod -Method Post -Uri https://abctech.com/api/2.0/run
-Body ($Params|ConvertTo-Json) -ContentType application/json -Headers
$headers
The response will be 2 value. E.g., id=10, queue=15
I am now taking only the id response.
GET:
$getrunidvalue=$getrunid.id
$getcheck=Invoke-RestMethod -Method Get -Uri
https://abctect.com/api/2.0/jobs/runs/get?id=$getrunidvalue -ContentType
application/json -Headers $headers
echo $getcheck
This gives the result as below.
id1 : 38
run_id : 1
number_in_job : 6
original_attempt_run_id : 217
state : #{life_cycle_state=TERMINATED;
result_state=SUCCESS; state_message=}
task : #{notebook_task=}
From this result I need to take the value of result_state.
I am not finding ideas on how to do that, can someone help.
Thanks
Expected result would be the result_state SUCCESS or FAILED.
It looks like the state is a hashtable that contains an entry result_state that you want to retrieve. You can access it using:
$getcheck.state.result_state

Resources