PowerShell Error when queuing a build via Invoke-RestMethod and put - powershell

Getting this error when trying to update a role to an endpoint using Powershell. It is crating the endpoints, just the roles update is giving error. same role update api call command works from postman.
$ApplyRole="https://Myorg/_apis/securityroles/scopes/distributedtask.serviceendpointrole/roleassignments/resources/72505f4d-564c-41cf-14508b977f52_f6a1c4f9-a043-4399-1aad7b5cf19c/?api-version=5.0-preview"
$ApplyRole = "https://Myorg/_apis/securityroles/scopes/distributedtask.serviceendpointrole/roleassignments/resources/72505f4d-564c-41cf-14508b977f52_f6a1c4f9-a043-4399-1aad7b5cf19c/?api-version=5.0-preview"
$Body1 = #{
roleName = "User"
userId = "f0e736e3-0e73-4fd2-8b7a-615126eac692"
}
$Bodyjson = $Body1 | ConvertTo-Json
Invoke-RestMethod -uri $ApplyRole -Method Put -Credential $mycreds -Body $Bodyjson -ContentType "application/json"
Error:
Invoke-RestMethod : {"$id":"1","innerException":null,"message":"Object reference not set to an instance of an object.","typeName":"System.NullReferenceException,
mscorlib","typeKey":"NullReferenceException","errorCode":0,"eventId":0}

Thanks for the reply.
Actually it was an issue with the body syntax.
Added like this and it works.
$Body1 = #"
[{
"roleName":"User",
"userId":"f0e736e3-0e73-4fd2-8b7a-615126eac692"
}]"#

Open pipeline definition->click the tab variables->add variable pat and change variable type to secret.
Add task powershell and enter the script.
$connectionToken="$(pat)"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$ApplyRole = "https://Myorg/_apis/securityroles/scopes/distributedtask.serviceendpointrole/roleassignments/resources/{project id}_{endpoint id}/?api-version=5.0-preview"
$body ="[{
`"roleName`": `"User`",
`"userId`": `"{group or user id}`"
}]"
$Roles = Invoke-RestMethod -Uri $ApplyRole -ContentType "application/json" -Body $body -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method PUT
Result:

Related

Create annotated tag with build user

I have powershell script which is creating annotated tag for commit in azure repos, but when I run this script in azure release pipeline I got error: "The combination of parameters is either not valid or not complete." When I make call from Postman with my credentials. its working. I also set repo permission Create Tag to Allow. Which permission I need for creating annotated tags with build user?
$createTagUrl= "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECT/_apis/git/repositories/$($env:BUILD_REPOSITORY_ID)/annotatedtags?api-version=6.0-preview.1"
Write-Host "createTagUrl=" $createTagUrl
$jsonObject = #"
{
"name": "$($env:RELEASE_RELEASENAME)-$(ENVIRONMENT)",
"taggedObject":{
"objectId": "$($env:BUILD_BUILDID)"
},
"message": "test"
}
"#
Write-Host "JsonObject: " $jsonObject
$json = #($jsonObject) | ConvertTo-Json -Depth 99
$createdTag = Invoke-RestMethod -Uri $createTagUrl -Method Post -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
I can reproduce your issue:
The root cause is the code on your side is wrong.
This should works:
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Basic <PAT>")
$headers.Add("Content-Type", "application/json")
$body = "{
`n `"name`": `"xxx`",
`n `"message`": `"xxx`",
`n `"taggedObject`": {
`n `"objectId`": `"<object id>`"
`n }
`n}"
$response = Invoke-RestMethod 'https://dev.azure.com/<Organization Name>/<Project Name>/_apis/git/repositories/<Repo Name>/annotatedtags?api-version=4.1-preview.1' -Method 'POST' -Headers $headers -Body $body
$response | ConvertTo-Json

Powershell script Trigger an release pipeline using Devops API

I am trying to create a Powershell script create a new release using DevOps API.
I can see the pipeline information using invoke rest method but not able to trigger a pipeline. Can I get some assistance here.?
Thanks,
Venkatraman
It's not documented very well, but to start the release you have to update the status to inProgress.
$updateReleaseUri = "$($vrsmBaseUri)_apis/Release/releases/$($releaseId)/environments/$($environmentId)?api-version=6.0-preview"
$updateReleaseJsonBody = #{status = 'inProgress' }
$updateReleaseJsonBody = $updateReleaseJsonBody | ConvertTo-Json -Depth 100
Invoke-RestMethod -Uri $updateReleaseUri -Method Patch -Headers $headers -Body $updateReleaseJsonBody -ContentType 'application/json'
Ref: https://learn.microsoft.com/en-us/rest/api/azure/devops/release/releases/update-release-environment?view=azure-devops-rest-6.0
You can use the specific endpoint "Releases - Create" to trigger the release pipeline.
The required parameter you need to provide at least to this endpoint is the definitionId of the release pipeline that you want to trigger.
Below is the complete PowerShell script of a demo as reference. I have tested with this script, and it can work well as expected.
$pat = '{Personal Access Token}'
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $pat)))
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", ("Basic {0}" -f $base64AuthInfo))
$headers.Add("Content-Type", "application/json")
$uri = "https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases?api-version=6.0"
$body = '{ "definitionId": {definitionId} }'
Invoke-RestMethod -Uri $uri -Headers $headers -Body $body -Method POST | ConvertTo-Json -Depth 10

Invoke-RestMethod to acces Joe SandBox API

I'm trying to create a powershell script to access JoeSandBox API to download reports.
I'm following their API details there https://www.joesandbox.com/userguide?sphinxurl=usage/webapi.html
Here's the beginning of the REST script I've put together:
$json = #{
apikey="XXXX";
webid= "YYYY"
} | ConvertTo-Json
invoke-restmethod -uri 'https://www.joesandbox.com/api/v2/analysis/download' -Method POST -Body $json -ContentType 'multipart/form-data'
Basically, I don't get the access...
Invoke-RestMethod : {"errors":[{"code":2,"message":"apikey is required."}]}
Thanks
$body = #{'apikey'='XXX'; 'webid'='YYY'}
invoke-restmethod -uri 'https://www.joesandbox.com/api/v2/analysis/download' -Method POST -body $body

how to update only one field in body request?

I'm trying to update a release pipeline's description using the provide Rest API documentation.
How should I send a 'Put' request in order to update a field?
I've tried to manually modify and capture the request using sniffer, it seems that my code does exactly the same.
$theBody = ConvertTo-Json #{description='Added a description'}
$instance = "tfs:8080"
$collection = "Collection"
$project = "myProject"
$releaseID = 1234
$apiVersion = "?api-version=4.1-preview.6"
$URI = "http://"+$instance+"/"+$collection+"/"+$project+"/_apis/release/releases/"+$releaseID+$apiVersion
$res= Invoke-RestMethod -Method Put -Uri $URI -UseDefaultCredentials -Body $theBody -ContentType 'application/json'
write-output $res
I'm getting an error message:
the Id of the Release does not match the Id of the original release
resource. Make sure that you are trying to update the correct resource
The best way to do it is to get the release with the same URL but with Get method (and without body):
$release = Invoke-RestMethod -Method Get-Uri $URI -UseDefaultCredentials -ContentType 'application/json'
Then modify the description:
$release.description = "Added a description"
Convert the release to JSON:
$theBody = $release | ConvertTo-Json -Depth 10
And do the Put:
$res = Invoke-RestMethod -Method Put -Uri $URI -UseDefaultCredentials -Body $theBody -ContentType 'application/json'

How do I access the value of a field returned by a Restful API

I have a very basic requirement to call a RESTful API. I am currently on a Windows 2012 R2 server using version 4 of PowerShell.
Here is my code:
$logon = #{
username = 'blah'
password='blah'
}
$body = $logon | ConvertTo-Json
$URI = 'https://URL/Logon'
Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose
I get the following result:
{"LogonResult":"blahblahblah"}
How do I extract just the logon token to reuse as a variable? I've already put a variable at the beginning of the command:
$token = (Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).content
This returns the entire result, not just the token. How do I get just the token as a result?
You can get the value of the returned LogonResult property as follows:
$token = ((Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).content | ConvertFrom-JSON).LogonResult
Or you simplify this by using Invoke-RestMethod as this returns just the content and converts it to a PSObject automatically:
$token = (Invoke-RestMethod -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).LogonResult