Add if-then-else logic to Azure DevOps release pipeline - azure-devops

I have a release pipeline in Azure DevOps.
I have added an Agentless job running that calls a REST API endpoint.
At the moment this works as expected.
However my next challenge is to take the response from the API call and perform some tasks. Here is a breakdown of the logic I am trying to achieve:
GET list of students (Connect to REST API with GET)
Read response from above step and look for a specific value
If value exists continue
If value does not exist then POST new value to REST API endpoint
Like I said, I have step 1 sorted but I do not know how to add the if-then-else logic
Any help appreciated
Thanks

You need to look at the output of your response to get your specific value.
$reponse = Invoke-RestMethod -Method GET -URI $url
$specificValue = $response.output.specificValue
if(!$specificValue) {
##value does not exist
Invoke-RestMethod -Method POST -URI $url -Body $body
}

Related

Graphi API - Creating Document Set with Invoke-RestMethod

I need some help to get my code to create a Document Set in SharePoint Online using Graph API directly from a PowerShell script using Invoke-RestMethod.
I tested the request under the Graph Explorer portal and it works fine and I get a nice HTTP 201 (OK) as seen on the picture below:
Trying the very same request from my PowerShell script fails and returns HTTP 400 (Bad Request), I can't get the folder created and that is the first step to get the document set created, according to my research and an example found here:
Is it possible to create a project documentset using graph API?
As the first step mentioned in the example above, I need to first create the folder and then proceed to the following steps to achieve the creation of the document set but I can't get this first step done.
My application has the necessary permissions as I tested in the Graph Explorer:
Files.ReadAndWrite.All
Sites.ReadAndWrite.All
Sites.FullControl.All (not required but I had to try this one to make sure!)
I'm on the second step (folder creation) and I can't get past this point, according to the link above, once I get this working I will need to get the new folder ID, and then send a new PATCH to alter its content type to match the desire document set, I hope I can get some help, all the examples are vague and pretty much describe only on what to do but no actual functional code to sample from.
Thanks in advance!
$uri = "https://graph.microsoft.com/v1.0/drives/b!yVnguUBzyUC1PxgTM0JP-_ERFp1PTZFCjycaWZK6yKulBi9Ce_J8RIfF-OkWKE4B/root/children"
$headers = #{
"Authorization" = "$($token.token_type) $($token.access_token)"
"Content-Type" = "application/json"
}
$body = #{
"name" = "Test"
"folder" = {}
"#microsoft.graph.conflictBehavior" = "rename"
}
$request = Invoke-RestMethod -Headers $headers -Body $body -Method Post -Uri $uri
It should work when you modify $body like this
$body = #{
"name" = "Test"
"folder" = #{}
"#microsoft.graph.conflictBehavior" = "rename"
} | ConvertTo-Json
$body is a JSON object and you need to convert it to JSON. For initialing an empty folder object you have to use #{} instead of {}.
Thanks #user2250152, you gave me a great idea by solving part of the problem!
I did add the conversion to JSON as you recommended and decided to add the content-type back to my original header and it did the trick!
Adding the content-type solved the issue but your collaboration was essential, so thank you very much!
Now wish me luck to get the other steps done and achieve the conclusion of this thing!
$headers = #{
"Authorization" = "$($token.token_type) $($token.access_token)"
"Content-Type" = "application/json"
}

How can I find all work items in a given board column via Azure DevOps API?

I’m building an application that fetches information from our Azure DevOps board. One of the tasks is to get all tickets present in a given column.
I’ve spent quite a lot of time reading through their docs but all the methods rely on you passing the IDS you want to get back, while what I’m looking for is for the API to tell me what work items do exist in a given column.
The easiest way to find the work items in a board column would be to use the Wiql - Query by Wiql API. The usage will look very similar to how you just use the UI query functionality to find work items.
Given some work items in this kind of board state (using Basic template):
Example in PowerShell below:
$AzureDevOpsAuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AzureDevOpsPAT)")) }
$uri = "https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/wiql?api-version=6.0"
$body = #{
"query" = "Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.BoardColumn] = 'Doing'"
} | ConvertTo-Json -Depth 10
Invoke-RestMethod -Method Post -Uri $uri -Headers $AzureDevOpsAuthenicationHeader -Body $body -ContentType 'application/json' |
Select-Object -ExpandProperty workItems
Returns:
id url
-- ---
26 https://dev.azure.com/{organization}/{project}/_apis/wit/workItems/26

Azure DevOps Rest API in Powershell saying no parameters matching

I am starting to use PowerShell to call the Azure DevOps REST API. But it seems like when I try to add parameters it tell me:
A parameter cannot be found that matches parameter name
'repositoryId'
Here is what my call looks like in PowerShell. If I take out the parameter it works. What am I doing wrong?
Invoke-RestMethod -Uri 'https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=5.1' -repositoryId $repoId -Headers (my authentication) -Method Get
Per Microsoft's documentation this should work.
https://learn.microsoft.com/en-us/rest/api/azure/devops/build/builds/list?view=azure-devops-rest-5.1
repositoryId should be url parameter as Booga Roo mentioned. The error indicated that Repository type is missing.
You should add another parameter to your uri repositoryType={repositoryType}.So the uri should be like below.
Please check here for all repositoryTypes
https://dev.azure.com/{Organization}/{Project}/_apis/build/builds?repositoryId={id}&repositoryType=TfsGit&api-version=5.1
Addition:
You can get your repositoryId from URL of Repositories page under Repos in the Project Settings. Check below screentshot.
The Invoke-RestMethod cmdlet does not have a -repositoryId parameter. The phrasing and examples on the help page are for "URI Parameters" instead of PowerShell parameters. It means you need to build it into -Uri value instead of trying to use it directly.
I suggest using this:
Invoke-RestMethod -Uri "https://dev.azure.com/{organization}/{project}/_apis/build/builds?repositoryId={$repoId}&api-version=5.1" -Headers (my authentication) -Method Get
Side note: There are double quotes around this example URI. This is so the variable expansion for $repoId will occur and be properly interpreted as part of the URI. Using single quotes as in the original example will prevent this and treat it as a literal string value and won't perform any subsitutions.

How I can get attachments detail for my workitem using Azure DevOps Rest API

I am trying to get the list of the attachments against my workitem along with that I need, attachment count, attachments name. which are attached to my workitem. I tried to read the documentation of Azure DevOps I can see the following
https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/attachments?view=azure-devops-rest-5.0
It has Get, Create and List endpoints available. But to get it asks for the attachment ID which not available because no endpoint returns the attachment details.
Can you please guide me which API endpoint I can use to get the attachment details of a worktiem.
You should first to get the work item details with Work Items - Get Work Item Rest API:
GET https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id}
Note: to get the attachments details you need to add this to parameter the url:
$expand=all
Now in the results you will get the relations property, there you will find the attachments url, in the url you can find the id.
For example:
$url = https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/434?$expand=all&api-version=5.0
$workItem = Invoke-RestMethod -Uri $url -Method Get -ContentType application/json
$split = ($workitem.relations.url).Split('/')
$attachmentId = $split[$split.count - 1]
# Result: 1244nhsfs-ff3f-25gg-j64t-fahs23vfs
Now you can use the attachment api to download the attachment.

Checking if a Rest Call succeeds in PowerShell

I'm currently writing a PowerShell script that will remove all users from a tool via Rest API. The current script works as intended but is lacking in error handling. The only thing I want to check for is if the Rest Call is successfully completed. After googling, I couldn't really find much or maybe I'm searching the wrong terms. Any thoughts or direction is much appreciated!
Here's an example of code I've used successfully (assuming you've defined Uri, Headers, and Body if required - also note the Method here is set to Post):
try
{
Write-Verbose "Calling $Uri"
Invoke-RestMethod -Uri $Uri -Method Post -Headers $Headers -Body $Json -ContentType 'application/json' -ErrorAction Stop
}
catch
{
throw $_
}