问题
I'm using the Azure Dev OPS to trigger the build and deploy. I have angular code in GIT branch from which the build will be triggered and based on build# I need to update a file in TFS and check-in the same.
I have added the PowerShell task to read the build# from GIT branch. But I don't know the further steps to update the file and check-in the same in TFS branch.
Please suggest PowerShell commands to achieve the ablove mentioned tasks.
回答1:
Azure DevOps pipeline task to update a file and check-in TFS
You could invoke the REST API Pushes - Create to update the file and check-in the same in TFS branch with powershell scripts.
Go to the Agent Phase and select Allow Scripts to Access OAuth Token. See Use the OAuth token to access the REST API:
Add a PowerShell task in your build pipeline to get the latest commit on the branch you want to update the file and check-in:
GET https://{instance}/{collection}/{project}/_apis/git/repositories/{repositoryId}/commits?api-version=5.0&branch={BranchName}&$top=1update the file and check-in the same in TFS branch via REST API:
POST https://{instance}/{collection}/{project}/_apis/git/repositories/{repositoryId}/pushes?api-version=5.0
Body (application/json):
{
"refUpdates": [
{
"name": "refs/heads/$(BranchName)",
"oldObjectId": "[step 2 commit ID]"
}
],
"commits": [
{
"comment": "Added a few more items to the task list.",
"changes": [
{
"changeType": "edit",
"item": {
"path": "/tasks.md"
},
"newContent": {
"content": "# Tasks\n\n* Item 1\n* Item 2\n* Item 3\n* Item 4\n\nIf you need to add more, update this file and add them!",
"contentType": "rawtext"
}
}
]
}
]
}
As the test result:
Note:
- You need to parse quotes if file content contains quotes (\"test\"), the same as other special charters.
- Use the Repositories - List to get the
repositoryId.
Hope this helps.
回答2:
Based on the above suggestions. I have added the below mentioned code
$requestBody = @{
changes=
@(@{
item= @{
path= "$/SMT_Project/" + $branch + "/SMT/BPOSE_WebApp/Deal/LandingPage.aspx"
contentMetadata= @{
encoding= -1
}
}
changeType= "add"
newContent= @{
content= $EncodedText
contentType= "base64Encoded"
}
})
comment= "Updated LandingPage.aspx with script for deployment"
} | ConvertTo-Json -Depth 4
$headers = @{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
$headers.Add("Accept", 'application/json')
$requestBodyJson = ($requestBody | ConvertFrom-Json)
Write-Host 'headers - ' $headers
Write-Host 'requestBody - ' $requestBody
Write-Host 'requestBodyJson - ' $requestBodyJson
$postRes = Invoke-WebRequest -Uri https://dev.azure.com/sm10/_apis/tfvc/changesets?api-version=5.1 -ContentType "application/json" -Headers $headers -Method POST -Body $requestBody -Verbose
But I have not received and response from the web request also I have not received any errors. Please do let me know anything is missing.
来源:https://stackoverflow.com/questions/59304119/azure-devops-pipeline-task-to-update-a-file-and-check-in-tfs