You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell循环获取Build Definition ID数据时如何覆盖CSV而非追加

问题解决:PowerShell循环中实现单ID数据覆盖写入CSV

问题现象

循环处理多个Build Definition ID时,期望每个ID对应的数据写入独立CSV文件并覆盖原有内容,但当前代码会将所有ID的数据累积追加到文件中。

问题原因

$report数组未在每次循环开始时重置为空,导致每次迭代都会把新数据追加到之前的数组中,最终导出的CSV包含了所有循环的累积数据。

解决方法

在foreach($item in $alphadata)循环的起始位置添加$report = @(),确保每次循环只收集当前ID对应的数据,避免累积。

修改后的完整代码

param(
[string] $url = 
"https://dev.azure.com/tfs/Projects/<projectname",
[string] $PAT = "<PAT>"
)

$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PAT)"))
$header = @{authorization = "Basic $token"}

#Read XML File
[xml]$xmlfile = Get-Content -Path "File.xml" 
$data = $xmlfile | Select-Object -Property SkipUpdate, Version | Where-Object{ $_.'SkipUpdate' -eq 'False'}

#Read JSON Data for Starting Changeset and buildDefinitionId
$jsonData = Get-Content "project_configuration.json" | ConvertFrom-Json
$branchNames = $jsonData.projectConfig 

#Comparing the data got from XML and JSON and get only the data that we need
$metadata = $branchNames | Select-Object -Property name | Where-Object {$data.Version -eq $_.name}
$metadata.name

#Get the BuildDefinition ID , Start Chnageset and Branch Name of the Version whose SkipUpdate flag is set to False
$alphadata = $branchNames | Where-Object {$data.Version -eq $_.name}
$alphadata | Select-Object -Property buildDefinitionId, startChangeset, branch
$getEndChangesetCall="https://dev.azure.com/tfs/projects/<projectname>_apis/build/builds?api-version=2.0&statusFilter=completed&resultFilter=succeeded&definitions=<REPLACEBUILDDEFINITIONID>"

foreach($item in $alphadata)
{
    # 每次循环重置数组,避免数据累积
    $report = @()

    $newCall = $getEndChangesetCall.Replace("<REPLACEBUILDDEFINITIONID>", $item.buildDefinitionId)
    Write-Host "Calling API on $newcall"
    $changeset = Invoke-RestMethod -Uri $newcall -Method Get -ContentType "application/json" -Headers $header -Verbose
    $changeset | ConvertTo-Json | Out-File "<path-to-a-file>\ChangesetReq\$($item.builddefinitionId).json"
    $changeset.value.sourceVersion[0]                                                                                
    #Final API call
    $APIUrl= 'https://dev.azure.com/tfs/Projects/<ProjectName>/_apis/tfvc/changesets?searchCriteria.fromId=<FROMCHANGESET>&searchCriteria.toId=<TOCHANGESET>&$orderby=id asc&searchCriteria.itemPath=<PATHFILTER>'
    $replaceEntity = $APIUrl.Replace("<FROMCHANGESET>", $item.startChangeset).Replace("<TOCHANGESET>",$changeset.value.sourceVersion[0]).Replace("<PATHFILTER>",$item.branch)
    Write-Host "Final API Called on : $replaceEntity"
    $reportcall = Invoke-RestMethod -Uri $replaceEntity -Method Get -ContentType "application/json" -Headers $header -Verbose

    $reportcall | ConvertTo-Json | Out-File "<Path-to-the-file>\ChangesetReq\$($item.startChangeset).json"
    $reportcall.value | ConvertTo-Json | Out-Null

    $reportcall.value | Foreach-Object {
        $changesetTfs = $_.changesetId
        $authorName = $_.author.displayName
        $commentMade = $_.comment
        $date = $_.createdDate  
        [array] $report += $_.report| ForEach-Object {
            [pscustomobject] @{
                'ChangesetId'= $changesetTfs
                'Author'= $authorName
                'Comments'= $commentMade
                'Date Checked In' = $date 
            } 
                                
        }                  
    
    }
    Write-Host ($report | Format-Table -Force | Out-String) 

    $report | Export-CSV -Path ".\$($item.startChangeset).csv" -NoTypeInformation

}

说明

每次循环初始化$report = @()后,当前ID的API返回数据会重新填充到空数组中,导出CSV时只会包含当前ID的内容,原有文件会被新内容替换,实现单ID数据的独立覆盖写入。

内容的提问来源于stack exchange,提问作者Santoshkumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 23:03:07