Powershell - How to parse the response - azure

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

Related

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

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

Need to get a value in single quotes in the body section while calling a restapi through powershell

I'm using below script to call a RestAPi using powershell:
$cd = 12000
$Url = 'https://exampleSet/Set'
$Body = #{
OperationType = 'new'
Number = "'$($cd)'"
CdAspId = 'Z_CK_BUGFIX'
CdType = 'CA_106_4'
} | ConvertTo-Json
$headers = #{
'ContentType' = 'application/json'
'Accept' = 'application/json'
'APIKey' = 'abcdef'
}
Invoke-RestMethod -contentType "application/json" -Uri $url -Method Post -body $Body -Headers $headers
While execution, powershell task in Azure is showing me internal server error.
I need help in passing the value in the body as:
Number = '12000'
How can I get the values in body in single quotes. Please help in this.
As mentioned in the comments, JSON exclusively uses double-quoted string literals, so trying to create a JSON document with a property entry Number = '12000' doesn't make any sense - it wouldn't be valid JSON.
To force string encoding rather than a numerical value, simply surround the value with double-quotes in PowerShell:
$Body = #{
OperationType = 'new'
Number = "$cd"
CdAspId = 'Z_CK_BUGFIX'
CdType = 'CA_106_4'
} | ConvertTo-Json

connecting to azure rest api using powershell resulting in StatusCode : 203 StatusDescription : Non-Authoritative Information

I am able to connect fine to azure API's using a PAT token in postman, however am not able to authenticate using powershell.
After playing around with different authorization passing I am still stuck with getting the html page for the sign in returned. Here is a sample request I am making
Invoke-RestMethod https://feeds.dev.azure.com/xx/x/_apis/packaging/Feeds/x/Packages -Headers #{Authorization="Token :xxx"}
After much searching I came across https://www.opentechguides.com/how-to/article/azure/201/devops-rest-powershell.html. Here is a simplified snippet that allowed my request to go through successfully.
#enter your token in pat token
$pat = "xxx"
# Create header with PAT
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$header = #{authorization = "Basic $token"}
#enter your url in projects url
$projectsUrl = "https://feeds.dev.azure.com/xx/x/_apis/packaging/Feeds/x/Packages -Headers"
$projects = Invoke-RestMethod -Uri $projectsUrl -Method Get -ContentType "application/json" -Headers $header

Output variables in Azure DevOps release pipeline gates

How do I use output variables in Azure DevOps release pipeline gates?
I would like to output a variable equal to the value of something in the response of the HTTP request.
e.g. The http request will return { success: true, userId: 12345 }. I would like to set a variable for userId which I can use in the next HTTP request gate.
As of this time, however, outputting variables in Invoke REST API in gates is not supported.
The output variables section cannot output the custom defined variables, but only the variables defined by the task.
Unfortunately, this task does not define an output variable. You can see it in the screenshot:
There are no output variables associated with this task.
Maybe this isn't what you are looking for, but you can use Azure Powershell to invoke HTTP Request and output the value of response that way to a pipeline variable for use in subsequent steps.
Refer to this Stack Overflow Post: How to access the response of the InvokeRestAPI task from another job in an Azure DevOps pipeline?
$url = "https://vsrm.dev.azure.com/thecodemanual/$env:SYSTEM_TEAMPROJECTID/_apis/Release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.0"
$pipeline = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Bearer
$env:SYSTEM_ACCESSTOKEN"}
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
$buildNumber = $env:BUILD_BUILDNUMBER
$pipeline.variables.ReleaseVersion.value = $buildNumber
####****************** update the modified object **************************
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}

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

Resources