Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through JSON object, return specific object

Tags:

powershell

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?

like image 386
Peter Boomsma Avatar asked Jan 21 '26 12:01

Peter Boomsma


1 Answers

$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.

like image 121
Peter Boomsma Avatar answered Jan 25 '26 19:01

Peter Boomsma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!