简体   繁体   中英

Powershell - Skip/overwrite the data which is already fetched instead of appending

I am trying to fetch the data in a loop for multiple Build Definition IDs, for each time one Definition ID is called the set of data will be printed, for the next time it should only fetch the data for the Next Build Definition ID and print only that data, I mean it should overwrite the data in a separate file. But in my case its appending in a same csv file

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.buildDefinitionId
#$alphadata.startChangeset
#$alphadata.branch
$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)
{
$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

}

How to overwrite the data/fetch only one particular Definition ID data into a csv file.

Continuing from my comments:

If I understand your question correctly now, you can do this to first gather all information in a variable $report , then create several groups of that based on the ChangesetId and finally save all groups into several CSV files.

$report = $reportcall.value | Foreach-Object {
    # output the object to be collected in variable $report
    foreach ($item in $_.report) {
        [pscustomobject] @{
            'ChangesetId'     = $item.changesetId
            'Author'          = $item.author.displayName
            'Comments'        = $item.comment
            'Date Checked In' = $item.createdDate
        } 
    }                  
}

# group the array on property ChangesetId and export the items for each ID separately
$report | Group-Object ChangesetId | ForEach-Object { 
    $_.Group | Export-CSV -Path ".\$($_.Name).csv" -NoTypeInformation 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM