3

I'm using Azure Devops and I want to loop through a list of pull requests. I'm using this API request to retrieve a list of pull requests.

When I check the URL I see:

enter image description here

Which is correct. I have 3 open pull requests. What I want to do is check each object for a specific attribute called sourceRefName.

When there's a match I want to return the complete object:

enter image description here

I've tried:

$listOfPullRequestsURL = "https://dev.azure.com/*****/*****/_apis/git/repositories/*****/pullrequests?api-version=5.0"
$listOfPullRequests = Invoke-RestMethod -Uri $listOfPullRequestsURL -Headers @{Authorization = $pat } -Method Get
Write-Host $listOfPullRequests
Write-Host $listOfPullRequests | ConvertFrom-Json

ForEach ($object in $listOfPullRequests) {
    Write-Host "### OBJECT ###"
    Write-Host $object
    Write-Host $object.sourceRefName
}

And the result is:

enter image description here

How do I go through each object? And is it possible to return the whole object based on 1 attribute?

2 Answers 2

1
$listOfPullRequestsURL = "https://dev.azure.com/****/****/_apis/git/repositories/****/pullrequests?api-version=5.0"
$listOfPullRequests = Invoke-RestMethod -Uri $listOfPullRequestsURL -Headers @{Authorization = $pat } -Method Get

$listOfPullRequests.value | ForEach-Object {
    if ($_.sourceRefName -eq $env:BUILD_SOURCEBRANCH) {
        Write-Host $_
    }
}

This shows the correct JSON object.

Sign up to request clarification or add additional context in comments.

1 Comment

It seems PowerShell converts the response JSON into a PSCustomObject (which is why Write-Host displays it like a hashtable). As you've determined, the response payload exists within the PSCustomObject's System.Object[] property "value", so dereferencing it and passing the array to ForEach-Object gets the desired behavior. :)
0

I understood you already took care of it.

Just wanted to add here - to avoid these stuff, I personally think it's more clean and creates less trouble to use hashtables.

In Powershell v6 It's easy to convert to hashtable with the built-in ConvertFrom-Json flag -AsHashtable.

$hashPullRequests = $listOfPullRequests | ConvertFrom-Json -AsHashtable

and then loop over $hashPullRequests like any other hashtable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.