首页 > 解决方案 > PowerShell中的循环问题?

问题描述

我正在尝试从各种 Azure API 端点提取一些数据,但没有得到我需要的确切结果,因为我正在尝试利用循环。我正确地提取了所有项目名称,但没有正确点击“获取管道运行”以尝试提取 AzDo 中每个管道的最后一次运行的 id 和单个时间以及最后一次运行的 id。$id is 和 times 都是数组,因为它捕获多次运行,因此“[0]”获取索引中的第一个。我能做些什么来清理它并使其更有效率......并且实际工作。在这种状态下,它只会成功生成项目列表。

$personalToken = "****************************"
 
#Write-Host "Initialize authentication context" -ForegroundColor Yellow
$token = [System.Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($personalToken)"))
$header = @{authorization = "Basic $token" }

# Get projects 
$projecturl = "https://dev.azure.com/*******/_apis/projects?api-version=6.0"
$projects = Invoke-RestMethod -Uri $projecturl -Method Get -ContentType "application/json" -Headers $header

# Get pipeline runs
$runurl = "https://dev.azure.com/*********/$projectname/_apis/pipelines/$id/runs?api-version=6.0-preview.1"
$runs = Invoke-RestMethod -Uri $runurl -Method Get -ContentType "application/json" -Headers $header

foreach($project in $projects.value) {
    Write-Output $project.name
    $projectname = $project.name

foreach($run in $runs.value.pipeline.id) {
    Write-Output $runs.value.pipeline.id
    $lastrundate = $runs.value.pipeline.id
    $id = $runs.value.pipeline.id[0]

# Builds API call
$url = "https://dev.azure.com/********/$projectname/_apis/pipelines?api-version=6.0-preview.1"
$output = Invoke-RestMethod -Uri $url -Method Get -ContentType "application/json" -Headers $header
$output.value | Sort-Object id -Descending | ForEach-Object {
        Write-Host $_.name - $_.folder - $_.id - $_._links.web

        $obj = New-Object System.Object
        $obj | Add-Member -type NoteProperty -name LastRunDate -Value $lastrundate
        $obj | Add-Member -type NoteProperty -name ProjectName -Value $projectname
        $obj | Add-Member -type NoteProperty -name PipelineName -Value $_.name
        $obj | Add-Member -type NoteProperty -name PipelineFolder -Value $_.folder 
        $obj | Add-Member -type NoteProperty -name PipelineURL -Value $_._links.web
        $obj | Add-Member -type NoteProperty -name PipelineID -Value $_.id
        $obj | Select-Object LastRunDate, ProjectName, PipelineName , PipelineFolder , PipelineURL , PipelineID | Export-Csv -Append c:\Temp\****.csv
       }
    }

标签: azurepowershellazure-devopsazure-pipelinespipeline

解决方案


这一段很奇怪:

foreach($run in $runs.value.pipeline.id) {
    Write-Output $runs.value.pipeline.id
    $lastrundate = $runs.value.pipeline.id
    $id = $runs.value.pipeline.id[0]

在此处检查运行定义:https ://docs.microsoft.com/en-us/rest/api/azure/devops/pipelines/runs/list?view=azure-devops-rest-6.1#run

你可以使用类似的东西:

foreach($run in $runs.value) {
    Write-Output "Run Id" $run.id "Pipeline Id" $run.pipeline.id "Finidh Date" $run.finishedDate
    $lastrundate = $run.createdDate


#something here

}

推荐阅读