hitman126
hitman126

Reputation: 951

Powershell Foreach loop to iterate through API output and display variable values line by line

I am running some Azure DevOps API queries in Postman which successfully return the expected results, a snippet of which is shared below and represents only one of dozens of similar iterative output. For the purpose of this illustration,let us assume the snippet below of Id value 66, is only one of 100s.

        "id": 66,
        "buildNumber": "20210401.7",
        "status": "completed",
        "result": "succeeded",
        "queueTime": "2021-04-01T16:50:04.9218848Z",
        "startTime": "2021-04-01T16:50:15.3583291Z",
        "finishTime": "2021-04-01T16:50:53.7221605Z",

I am now looking to iteratively parse the 100+ records with a Powershell foreach loop, piping out the "id","buildNumber", "status" and "result" values line by line into an output file.

The desired output should look something like the below:

        "id": 66,
        "buildNumber": "20210401.7",
        "status": "completed",
        "result": "succeeded",

        "id": 65,
        "buildNumber": "20210331.5",
        "status": "completed",
        "result": "failed",

        "id": 64,
        "buildNumber": "20210331.4",
        "status": "completed",
        "result": "succeeded",

Any suggestions or ideas on how to achieve this would be most appreciated.

[[MY CURRENT POWERSHELL SCRIPT WITH PERSONAL VARIABLES EDITED OUT]]

$connectionToken="[MY-PAT]"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))

$url = 'https://dev.azure.com/[MY-AZURE-ORG]/[MY-TEAM-PROJECT]/_apis/build/builds?api-version=6.0'

$PackageInfo = (Invoke-RestMethod -Uri $url -Method Get -UseDefaultCredential -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}) 

$LatestVersion= $PackageInfo.value.buildnumber | Select-Object -first 1

$BuildResult= $PackageInfo.value.result | Select-Object -first 1


foreach ($item in $PackageInfo)
{
    Write-Host " " 
    Write-Host "Latest build = $LatestVersion" "|" "Build Result = $BuildResult"
    Write-Host " "  
}

[[OUTPUT FROM ABOVE SCRIPT]]

enter image description here

As can be seen from the above image, by retrieving the last build record, I get the above output returned by my Powershell script, which is great.

I am however not after only the last build record. I want all the build records listed line by line. Therefore, any refinement of my existing script to achieve this will ideally be what would be most suitable as it only requires a minor tweak in my opinion.

Omitting the Select-Object returns all of the expected data, but in the below format which isn't displayed in my preferred format of individual rows.

enter image description here

Upvotes: 0

Views: 3308

Answers (2)

Ravi Yadav G
Ravi Yadav G

Reputation: 37

$datepoint = "MAIN_20230601"
$accountingTypesArray = "AccruedExternalInterest","AccruedInternalInterest","AccruedFee"

foreach ($item in $accountingTypesArray)
{
    $finalUrl = "https://encx-eodd-test.net/api/Delivery/Trigger?accountingPoint="+$datepoint+"&productSystem=WSO&accountingType="+$item
   
 $response = Invoke-RestMethod $finalUrl -Method 'GET' 
    Write-Output $response.slideshow
}

Upvotes: 0

Vikram Dhanwani
Vikram Dhanwani

Reputation: 101

You are getting info for builds so I am assuming you are using below Azure DevOps API :

https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=6.0

Using PowerShell, firstly you will need to authenticate , You can use OAuth2 Authentication : Refer : https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops

PAT access method can be used but token needs to be manually generated from UI.

function getBearer([string]$TenantID, [string]$ClientID, [string]$ClientSecret)
{
  $TokenEndpoint = {https://login.windows.net/{0}/oauth2/token} -f $TenantID 
  $ARMResource = "https://management.core.windows.net/";

  $Body = @{
          'resource'= $ARMResource
          'client_id' = $ClientID
          'grant_type' = 'client_credentials'
          'client_secret' = $ClientSecret
  }

  $params = @{
      ContentType = 'application/x-www-form-urlencoded'
      Headers = @{'accept'='application/json'}
      Body = $Body
      Method = 'Post'
      URI = $TokenEndpoint
  }

  $token = Invoke-RestMethod @params

  Return "Bearer " + ($token.access_token).ToString()
}


    $header = @{
Authorization = getBearer $TenantId $ClientId $ClientSecret
content-type = 'application/json'
}

$ApiUri = "https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=6.0"

$data = (Invoke-RestMethod  -Uri $ApiUri -Method Get -Headers $header).value

$OutputFile = "<file-name>"

Class BuildObject {
    id [String]
    buildNumber [String]
    status [String]
    result [String]
}
$BuildObj = New-Object $BuildObject


foreach($buildItem in $data) {
    $BuildObj.id = $buildItem.id
    $BuildObj.buildNumber = $buildItem.buildNumber
    $BuildObj.status = $buildItem.status
    $BuildObj.result = $buildItem.result
    
    $BuildObj | OutFile -FilePath $OutputFile -Append
}
    

Upvotes: 0

Related Questions